Approach 1Optimal▶ Animated
Two rolling variables
F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2). Roll a pair forward n times.
You only need the last two values. Recursing from the top would recompute the same suffixes.
Algorithm
- If
n < 2, returnn. a, b = 0, 1; thena, b = b, a+bforn-1steps.- Return
b.
- Time
- O(n)
- Space
- O(1)
class Solution: def fib(self, n: int) -> int: if n < 2: return n a, b = 0, 1 for _ in range(2, n + 1): a, b = b, a + b return b