Fibonacci Number
The Fibonacci numbers form a sequence where F(0) = 0, F(1) = 1, and F(n) = F(n-1) + F(n-2) for n > 1. Given n, return F(n). Plain recursion recomputes F(2) an exponential number of times because the same subproblem is asked for over and over. Build the answer bottom-up from F(0) and F(1), reusing each earlier value exactly once.
Constraints
- 0 ≤ n ≤ 30
Example
n = 55Explanation F(5) = F(4) + F(3) = 3 + 2 = 5.
Build the Fibonacci table from F(0) up to F(n)
The whole table for n = 5 is laid out. F(0) = 0 and F(1) = 1 are the base cases; the rest are still blank.
What happens in this step
F(0) = 0 F(1) = 1 These are given directly by the problem, not computed. F(2) to F(5) are still blank — every one of them will be built from these two.
Steps to visualize
- Set the base cases: F(0) = 0 and F(1) = 1.
- For every i from 2 to n, set F(i) = F(i-1) + F(i-2).
- Each new value reuses the two cells directly before it.
- The value at F(n) is the answer.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
The whole table for n = 5 is laid out. F(0) = 0 and F(1) = 1 are the base cases; the rest are still blank.
What happens in this step
F(0) = 0 F(1) = 1 These are given directly by the problem, not computed. F(2) to F(5) are still blank — every one of them will be built from these two.
Solution
function fib(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let prev2 = 0;
let prev1 = 1;
for (let i = 2; i <= n; i++) {
const curr = prev1 + prev2;
prev2 = prev1;
prev1 = curr;
}
return prev1;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
n = 5 | 5 | example from the docstring |
n = 0 | 0 | smallest valid input, base case F(0) |
n = 1 | 1 | base case F(1) |
n = 2 | 1 | first value built from both base cases |
n = 4 | 3 | a few steps of accumulation |
n = 10 | 55 | a longer run of accumulation |
n = 30 | 832040 | upper bound of the constraint range |