Recursion: Fibonacci
easy 16 minFibonacci is the classic example of tree recursion: fib(n) = fib(n - 1) + fib(n - 2) with base cases fib(0) = 0 and fib(1) = 1.
Video lesson · Chapter 1 of 5
Two generations behind
Recursive Fibonacci — The echo foundry
1:26Reel
Read caption
A bat traces the nine calls for Fibonacci of four, hears the duplicate subproblem, and saves its result for a second request. One bell per number. Save its note and play it back.
How it works
Step through the idea, or press Play.
Stop at the base cases. fib(0) = 0 and fib(1) = 1 return straight away without calling anything
Understand it
Start here
What the Fibonacci sequence is
The Fibonacci sequence starts with 0 and 1, and every later number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, and so on. We write the -th number as , counting from .
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 |
It is the first example of tree recursion most people meet, and the first example of dynamic programming. If you have not met recursion yet, start with Recursion: Factorial, where each call makes just one smaller call.
The definition
Two base cases and one rule
The recurrence
Base case 1: fib(0) = 0
Stops the recursion at the bottom. Without it,
fib(2)would callfib(0), thenfib(-1), forever.Base case 2: fib(1) = 1
The other stopping point.
n <= 1withreturn nhandles both base cases in one line.The rule
Every other value is
fib(n - 1) + fib(n - 2): two smaller copies of the same problem.
The algorithm
How one call runs
One call of fib(n)
def fib(n): if n <= 1: # base cases: fib(0) = 0, fib(1) = 1 return n return fib(n - 1) + fib(n - 2)for i in range(8): print(f"fib({i}) = {fib(i)}")The picture
The call tree repeats itself
Call tree of fib(5)
| Call | Times called in fib(5) | Pattern |
|---|---|---|
fib(5) | 1 | |
fib(4) | 1 | |
fib(3) | 2 | |
fib(2) | 3 | |
fib(1) | 5 | |
fib(0) | 3 |
fib(n), fib(k) is called times for . The waste is itself Fibonacci-shaped.Tree recursion
Two recursive calls per call, so the calls branch into a binary tree.
Divide and conquer
Break the problem into two smaller copies and combine their answers with one addition.
Overlapping subproblems
The same smaller calls come up again and again. This is the property that makes caching pay off.
Complexity
A quick bound: O(2ⁿ)
Let be the work for fib(n). Each call does a constant amount of work plus its two calls, which gives a recurrence of the same shape as Fibonacci itself.
The cost recurrence
Squeeze it between two easy recurrences
The exact rate
Where φⁿ comes from
Count the calls exactly
How fast does F(n) grow?
The tight bound
fib(40) makes 331,160,281 calls.Space
The call stack is only n deep
Time counts every call that ever happens. Space counts only the frames alive at the same moment. A branch is finished and popped before its sibling starts, so the stack holds at most one root-to-leaf path: fib(n), fib(n-1), ..., fib(1), which is frames.
The stack while fib(4) runs
Fix 1
Memoisation: compute each value once
There are only different questions, fib(0) to fib(n). Memoisation keeps a dictionary of answers: look the answer up before computing, store it after. Every repeated subtree in the call tree collapses into a single lookup.
A memoised call
n reaches the bottom box at most once. For fib(5) that is 9 calls instead of 15; in general calls, time.from functools import cachedef fib_memo(n, memo=None): if memo is None: memo = {} # never write memo={} in the signature if n in memo: return memo[n] if n <= 1: return n memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo) return memo[n]@cachedef fib_cached(n): return n if n <= 1 else fib_cached(n - 1) + fib_cached(n - 2)print(fib_memo(50), fib_cached(90)) # instantFix 2
Bottom-up: a table, then two variables
Turn the recursion inside out. Fill dp[0] and dp[1], then dp[i] = dp[i - 1] + dp[i - 2] for . Each cell's inputs are already filled when you reach it, so there is no recursion and no stack. Since only the last two cells are ever read, two variables are enough.
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
dp[i] | 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 |
fib(7) takes 6 additions, one per cell from 2 to 7.def fib_table(n): if n <= 1: return n dp = [0] * (n + 1) dp[1] = 1 for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n]def fib_two_vars(n): a, b = 0, 1 # F(0), F(1) for _ in range(n): a, b = b, a + b # slide the pair one step return aprint(fib_table(7), fib_two_vars(7), fib_two_vars(100))Bottom-up loop
- time and space with two variables.
- No recursion, so no recursion limit.
- Needs you to work out the fill order first.
Naive recursion
- About calls:
fib(40)takes hundreds of millions. - Recomputes the same values again and again.
- Still uses stack, and hits the recursion limit.
Comparison
Every way to compute F(n)
| Approach | Time | Space | Notes |
|---|---|---|---|
| Naive recursion | , so | stack | Fine for or so; teaching only |
| Memoised recursion (top-down) | memo + stack | Keeps the recursive shape; depth limit applies | |
| Table (bottom-up) | Every value kept, handy if you need all of them | ||
| Two variables | The default answer in interviews | ||
| Matrix power or fast doubling | or | Squares a 2 × 2 matrix; good with a modulus | |
| Binet's formula with floats | arithmetic | Wrong past about from rounding |
Fast doubling: halve n each step
Pattern spotting
From Fibonacci to dynamic programming
Which version to write
Climbing stairs
Steps of 1 or 2: ways(n) = ways(n - 1) + ways(n - 2). It is .
Tiling a 2 × n board
The last tile is one vertical domino or two horizontal ones: the same recurrence.
House robber
Rob house plus best up to , or skip it and take best up to : Fibonacci shape with a max.
Recap
Key takeaways
Key points
- F(0) = 0, F(1) = 1, F(n) = F(n - 1) + F(n - 2). Both base cases are needed.
- Naive recursion is tree recursion: two calls per call, 2F(n + 1) - 1 calls in total.
- Its time is Θ(φⁿ) with φ ≈ 1.618, usually quoted as O(2ⁿ); its space is O(n) for the call stack.
- Only n + 1 distinct subproblems exist, so the tree is full of repeats: overlapping subproblems.
- Memoisation (top-down) and tabulation (bottom-up) both give O(n) time; two variables give O(1) space.
- Never use a mutable default argument as a memo; use None or @functools.cache.
- Fast doubling or matrix power computes F(n) in O(log n) multiplications.