Fibonacci Number
Fibonacci Number is LeetCode 509 (Easy). The sequence starts with F(0) = 0 and F(1) = 1, and every later term is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, … Given n, return F(n).
nis between 0 and 30, so the answer is at most F(30) = 832,040 and fits in a 32-bit int.
- 0 <= n <= 30
Intuition
To get the next term you only ever need the last two. So keep just a pair, prev = F(i − 1) and curr = F(i), and slide it one place to the right: the new pair is (curr, prev + curr). Starting from (F(0), F(1)) = (0, 1), after n − 1 slides curr holds F(n).
The definition written straight as recursion is correct but wasteful. fib(5) asks for fib(4) and fib(3), and fib(4) asks for fib(3) again. The repeats multiply at every level, so the number of calls grows about 1.6 times with each step of n. The loop computes each term exactly once.
A sequence where each term depends on a fixed number of earlier terms. Keep only that many values and roll them forward, instead of a table or a recursion tree.
Approach
Before reading on, count how many times plain recursion computes fib(2) while finding fib(6). Then write a loop that keeps only two numbers. Aim for O(n) time and O(1) space.
Two ways to solve it
Keep the last two terms and slide them forward n − 1 times.
- Each term once: no repeated work.
- Two numbers of memory: no table, no call stack.
The answer interviewers expect.
Write the recursive definition, but store each F(k) the first time it is computed and reuse it.
- Reads like the maths: the code is the formula.
- Cost: a memo of
n + 1values plus a call stackndeep.
The standard first step from plain recursion to dynamic programming.
Both compute each term once. The loop needs only two variables, while the memo keeps every term and recurses n levels deep. The steps, code and live demo follow the loop, and the memo code comes after the demo.
Return n when it is 0 or 1
F(0) = 0 and F(1) = 1, so return n covers both. The loop below starts from a ready-made pair, so these two cases must be answered before it.
Start the pair at F(0) and F(1)
Set prev, curr = 0, 1. The loop always keeps prev = F(i − 1) and curr = F(i), starting with i = 1.
Slide the pair n − 1 times
Each round sets prev, curr = curr, prev + curr, moving i up by one. Python evaluates the whole right side before assigning, so both new values use the old pair. In C++ and Java, store prev + curr in a temporary first.
Return curr
The pair started at i = 1 and moved n − 1 times, so i = n and curr is F(n).
Code in Python, C++ and Java
return n answers both before the loop is reached.Recursion with a memo
The recursive definition, with each value cached the first time it is computed. Every later request for the same k is answered from the cache, so only n + 1 distinct calls do real work.
Common pitfalls
Updating the pair one variable at a time
prev = curr curr = prev + curr
prev, curr = curr, prev + curr
After the first line prev already equals curr, so the second line doubles curr instead of adding the old prev. The pair becomes 1, 2, 4, 8, … and n = 5 returns 16 instead of 5.
Sliding the pair one time too many
for _ in range(n):
for _ in range(n - 1):
The pair already starts at F(1), so only n − 1 slides are needed. One extra slide returns F(n + 1): n = 2 gives 2 instead of 1.
Complexity
Fibonacci Number FAQ
Why is plain recursion slow if n is only 30?
It still passes at 30, but fib(30) makes 2,692,537 calls to produce 31 different values. The call count is 2 · F(n + 1) − 1, so it grows like the sequence itself: n = 50 would need about 40 billion calls, while the loop needs 49 additions.
How do I print the Fibonacci series in Python?
Use the same pair, but print the smaller number before each slide. Start with a, b = 0, 1, then repeat print(a, end=" ") and a, b = b, a + b inside for _ in range(10). That prints the first 10 terms: 0 1 1 2 3 5 8 13 21 34.
Is there a faster way for very large n?
Yes. Raising the matrix [[1, 1], [1, 0]] to the power n by repeated squaring gives F(n) in O(log n) multiplications, and fast doubling does the same with plain formulas. Binet's closed formula uses floating point and stops being exact around n = 70. In a 32-bit int the largest term is F(46); F(47) already overflows.