Fibonacci Number (LeetCode 509): Solution and Explanation

Easy
Math
Dynamic Programming
Recursion
Memoization

The Fibonacci sequence starts with F(0) = 0 and F(1) = 1, and each later term is the sum of the two before it. Given n between 0 and 30, return F(n).

Intuition

The definition is already code: fib(n) = fib(n - 1) + fib(n - 2) with base cases 0 and 1. Written as plain recursion it gives the right answer, but each call spawns two more, so the call tree roughly doubles at every level. For n = 30 that is about 2.7 million calls to produce one number.

Most of those calls are repeats. fib(5) calls fib(4) and fib(3), and fib(4) calls fib(3) again. Lower down, fib(2) shows up many times. The tree recomputes the same handful of subproblems over and over, which is the signal that dynamic programming applies.

Memoizing the recursion fixes the repeats, but the cleaner observation is about order. If you compute the terms from the bottom, F(0), F(1), F(2) and so on, every term you need is already known when you reach it. And each new term reads only the two terms just before it, so everything older can be thrown away.

That leaves two variables. a holds F(i - 2), b holds F(i - 1), the next term is a + b, and then both slide one step to the right. After the loop reaches n, b is the answer.

Approach: Bottom-up with two rolling variables

  1. If n < 2, return n, since F(0) = 0 and F(1) = 1.
  2. Set a = 0 and b = 1, the values of F(0) and F(1).
  3. For i from 2 to n, compute a + b, which is F(i).
  4. Shift the window: a takes the old b and b takes the new sum. Now a is F(i - 1) and b is F(i).
  5. When the loop finishes, b holds F(n). Return it.

Step-by-step example

n = 2
  1. n is 2, which is not a base case, so the loop runs.
  2. Start with a = 0 (F(0)) and b = 1 (F(1)).
  3. i = 2: the sum a + b is 0 + 1 = 1, which is F(2).
  4. Shift: a becomes 1 (F(1)) and b becomes 1 (F(2)).
  5. The loop ends because i reached n, so the function returns b = 1.

Code: Python, Java, C++

1class Solution:
2    def fib(self, n: int) -> int:
3        if n < 2:
4            return n
5        a, b = 0, 1
6        for _ in range(2, n + 1):
7            a, b = b, a + b
8        return b
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Matrix exponentiation O(log n)
Bottom-up with two rolling variables O(n)
Memoized recursion or DP array O(n)
Plain recursion O(2^n)
Time

O(n)

The loop runs n - 1 times and each iteration does one addition and two assignments.

Space

O(1)

Only a and b are kept, no matter how large n is. There is no array and no recursion stack.

Other approaches

Plain recursion (time O(2^n), space O(n))

Translate the definition directly. It is the easiest to write and explains the recurrence, but it recomputes the same subproblems so often that the number of calls grows like the Fibonacci numbers themselves.

Memoized recursion or DP array (time O(n), space O(n))

Cache each F(k) the first time it is computed, either in a hash map behind the recursion or in a table filled from index 0 upward. Each value is computed once, but you keep all n of them when only two are ever read again.

Matrix exponentiation (time O(log n), space O(1))

Raise the matrix [[1,1],[1,0]] to the power n with repeated squaring and read F(n) from the result. It is faster for very large n, though for n up to 30 the simple loop is shorter and just as quick.

Common mistakes

  • Forgetting n = 0. Starting the loop with a = 0, b = 1 and returning b gives 1 for n = 0 unless the base case returns n first.
  • Updating the two variables in the wrong order in languages without tuple assignment. Writing a = b; b = a + b; uses the new a and doubles b. Save the sum in a temporary first.
  • Off-by-one loop bounds. The loop must include n itself, so it runs from 2 to n inclusive.
  • Submitting the plain recursion for larger inputs. It passes n = 30 in some languages but is far slower than it needs to be, and the same pattern times out on related problems.

Frequently asked questions

Why is naive recursion for Fibonacci so slow?

Each call makes two more calls, and the same subproblems appear in many branches. Computing F(n) this way makes 2F(n + 1) - 1 calls, which grows exponentially, roughly 1.6 to the power n.

Why are two variables enough?

The recurrence for F(i) reads only F(i - 1) and F(i - 2). Once you have moved past an index, nothing later ever looks at it again, so storing more than the last two values is wasted memory.

Can the answer overflow a 32-bit integer?

Not within the constraints. F(30) is 832040, far below the 32-bit limit. F(46) is the largest Fibonacci number that fits in a signed 32-bit int.

How does this relate to Climbing Stairs?

Climbing Stairs follows the same recurrence, since the ways to reach step n are the ways to reach n - 1 plus the ways to reach n - 2. Only the starting values differ, so the same two-variable loop solves both.