Fibonacci Number
Difficulty: Easy · Pattern: 1-D Dynamic Programming · LeetCode #509
Return F(n), where F(0) = 0, F(1) = 1 and F(n) = F(n−1) + F(n−2).
Examples
text
n = 2 → 1
n = 3 → 2
n = 4 → 3Hints
- Naive recursion recomputes the same values exponentially often. Draw the call tree for n = 5.
- You only ever need the last two values.
Approach
This is the "hello world" of DP, and it shows the three implementation styles:
| Style | Time | Space |
|---|---|---|
| Naive recursion | O(φⁿ) ≈ O(1.618ⁿ) | O(n) |
| Memoized recursion (top-down) | O(n) | O(n) |
| Tabulation with two variables (bottom-up) | O(n) | O(1) |
The rolling update is a, b = b, a + b. There's also an O(log n) method: fast exponentiation of the matrix [[1,1],[1,0]].
Complexity
Time: O(n). Space: O(1).
Python solution
def fib(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return aJavaScript solution
function fib(n) {
let a = 0, b = 1;
for (let i = 0; i < n; i++) [a, b] = [b, a + b];
return a;
}