Fibonacci Number

The Fibonacci numbers, written F(n), form a sequence where each number is the sum of the two before it, starting from 0 and 1. So F(0) = 0, F(1) = 1, and F(n) = F(n - 1) + F(n - 2) for n > 1. Given n, return F(n).

30:00

Fibonacci Number
easy
Free written solution
Topics
Companies

The Fibonacci numbers, written F(n), form a sequence where each number is the sum of the two before it, starting from 0 and 1. So F(0) = 0, F(1) = 1, and F(n) = F(n - 1) + F(n - 2) for n > 1. Given n, return F(n).

Example 1:
Input: 2
Output: 1
Constraints:
  • 0≤n≤300 \leq n \leq 30

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr =2

Naive recursion: fib(2) calls fib(1) and fib(0), and each of those splits again.

Naive recursion: fib(2)

base case

repeated work

calls: ?

210

Bottom-up: two rolling variables

loop steps: 1

?

F(0)

?

F(1)

?

F(2)

a = -
b = -
Variables
VariableValue
n2
level0
DepthFunction Call
Stack empty
0/8