AlgoViz

Recursion: Fibonacci

easy 16 min

Fibonacci 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

0:00 / 4:01

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.

Step 1 of 3

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 nn-th number as F(n)F(n), counting from F(0)=0F(0) = 0.

n0123456789
F(n)F(n)0112358132134
Each entry is the sum of the two to its left: F(7)=8+5=13F(7) = 8 + 5 = 13.

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

F(n)={0n=01n=1F(n−1)+F(n−2)n≥2F(n) = \begin{cases} 0 & n = 0 \\ 1 & n = 1 \\ F(n-1) + F(n-2) & n \ge 2 \end{cases}
The definition is already recursive, so the code is a direct translation of it.
  • Base case 1: fib(0) = 0

    Stops the recursion at the bottom. Without it, fib(2) would call fib(0), then fib(-1), forever.

  • Base case 2: fib(1) = 1

    The other stopping point. n <= 1 with return n handles 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)

Six moves: check the base cases, return if one matches, call n - 1, wait, call n - 2, add and return.
Python
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 naive recursive version: a word-for-word copy of the definition.
Edit and run it in your browser

The picture

The call tree repeats itself

Call tree of fib(5)

15 calls for 6 distinct questions. Everything in red is work that was already done somewhere else in the tree.
CallTimes called in fib(5)Pattern
fib(5)1F(1)F(1)
fib(4)1F(2)F(2)
fib(3)2F(3)F(3)
fib(2)3F(4)F(4)
fib(1)5F(5)F(5)
fib(0)3F(4)F(4)
Inside fib(n), fib(k) is called F(n−k+1)F(n - k + 1) times for k≥1k \ge 1. 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 T(n)T(n) be the work for fib(n). Each call does a constant amount of work cc plus its two calls, which gives a recurrence of the same shape as Fibonacci itself.

The cost recurrence

T(n)=T(n−1)+T(n−2)+c,T(0)=T(1)=cT(n) = T(n-1) + T(n-2) + c, \qquad T(0) = T(1) = c

Squeeze it between two easy recurrences

2 T(n−2)⏟since T(n−1) ≥ T(n−2)  ≤  T(n)  ≤  2 T(n−1)+c⏟since T(n−2) ≤ T(n−1)⟹Ω(2n/2)≤T(n)≤O(2n)\underbrace{2\,T(n-2)}_{\text{since } T(n-1) \,\ge\, T(n-2)} \;\le\; T(n) \;\le\; \underbrace{2\,T(n-1) + c}_{\text{since } T(n-2) \,\le\, T(n-1)} \quad\Longrightarrow\quad \Omega\big(2^{n/2}\big) \le T(n) \le O\big(2^{n}\big)
Replace the smaller call by the bigger one and the cost at most doubles per level: O(2n)O(2^n). Replace the bigger by the smaller and it doubles every two levels: at least 2n/2≈1.414n2^{n/2} \approx 1.414^n. Either way it is exponential.

The exact rate

Where φⁿ comes from

Count the calls exactly

C(n)=C(n−1)+C(n−2)+1,C(0)=C(1)=1⟹C(n)=2F(n+1)−1C(n) = C(n-1) + C(n-2) + 1,\quad C(0) = C(1) = 1 \quad\Longrightarrow\quad C(n) = 2F(n+1) - 1
Check: C(5)=2⋅8−1=15C(5) = 2 \cdot 8 - 1 = 15, C(10)=2⋅89−1=177C(10) = 2 \cdot 89 - 1 = 177, C(20)=2⋅10946−1=21,891C(20) = 2 \cdot 10946 - 1 = 21{,}891. The call count is just twice a Fibonacci number.

How fast does F(n) grow?

try F(n)≈xn:xn=xn−1+xn−2  ⇒  x2=x+1  ⇒  x=φ=1+52≈1.618\text{try } F(n) \approx x^n:\quad x^n = x^{n-1} + x^{n-2} \;\Rightarrow\; x^2 = x + 1 \;\Rightarrow\; x = \varphi = \frac{1 + \sqrt{5}}{2} \approx 1.618
The other root, ψ=1−52≈−0.618\psi = \frac{1 - \sqrt{5}}{2} \approx -0.618, shrinks towards zero. That gives Binet's formula F(n)=φn−ψn5F(n) = \frac{\varphi^n - \psi^n}{\sqrt{5}}.

The tight bound

T(n)=Θ(C(n))=Θ(F(n+1))=Θ(φn)≈Θ(1.618n)  ⊂  O(2n)T(n) = \Theta\big(C(n)\big) = \Theta\big(F(n+1)\big) = \Theta(\varphi^{n}) \approx \Theta(1.618^{n}) \;\subset\; O(2^{n})
So O(2n)O(2^n) is a true but loose upper bound. Each +1 to nn multiplies the work by about 1.618, not 2. Still exponential: 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 nn frames.

The stack while fib(4) runs

Nine calls happen over time, but the stack never holds more than four frames: O(n)O(n) space.

Fix 1

Memoisation: compute each value once

There are only n+1n + 1 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

Each n reaches the bottom box at most once. For fib(5) that is 9 calls instead of 15; in general 2n−12n - 1 calls, O(n)O(n) time.
Python
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))   # instant
Two ways to memoise. The decorator does the lookup and the store for you.
Edit and run it in your browser

Fix 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 i=2,3,…,ni = 2, 3, \dots, n. 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.

i01234567
dp[i]011235813
Filling the table for fib(7) takes 6 additions, one per cell from 2 to 7.
Python
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))
Tabulation in O(n)O(n) space, then the same idea in O(1)O(1) space.
Edit and run it in your browser

Bottom-up loop

  • O(n)O(n) time and O(1)O(1) space with two variables.
  • No recursion, so no recursion limit.
  • Needs you to work out the fill order first.

Naive recursion

  • About φn\varphi^n calls: fib(40) takes hundreds of millions.
  • Recomputes the same values again and again.
  • Still uses O(n)O(n) stack, and hits the recursion limit.

Comparison

Every way to compute F(n)

ApproachTimeSpaceNotes
Naive recursionΘ(φn)\Theta(\varphi^n), so O(2n)O(2^n)O(n)O(n) stackFine for n≤30n \le 30 or so; teaching only
Memoised recursion (top-down)O(n)O(n)O(n)O(n) memo + stackKeeps the recursive shape; depth limit applies
Table (bottom-up)O(n)O(n)O(n)O(n)Every value kept, handy if you need all of them
Two variablesO(n)O(n)O(1)O(1)The default answer in interviews
Matrix power or fast doublingO(log⁡n)O(\log n)O(1)O(1) or O(log⁡n)O(\log n)Squares a 2 × 2 matrix; good with a modulus
Binet's formula with floatsO(1)O(1) arithmeticO(1)O(1)Wrong past about n=70n = 70 from rounding
Times count additions and multiplications as O(1)O(1). F(n)F(n) has about 0.694n0.694n bits, so for huge nn the big-number arithmetic itself adds cost.

Fast doubling: halve n each step

F(2k)=F(k) (2F(k+1)−F(k)),F(2k+1)=F(k)2+F(k+1)2F(2k) = F(k)\,\big(2F(k+1) - F(k)\big), \qquad F(2k+1) = F(k)^2 + F(k+1)^2
From F(k)F(k) and F(k+1)F(k+1) you get F(2k)F(2k) and F(2k+1)F(2k+1) in a few multiplications, so nn is reached in O(log⁡n)O(\log n) steps, the same idea as fast exponentiation.

Pattern spotting

From Fibonacci to dynamic programming

Which version to write

Overlapping subproblems plus an answer built from smaller answers is exactly what dynamic programming means.
  • Climbing stairs

    Steps of 1 or 2: ways(n) = ways(n - 1) + ways(n - 2). It is F(n+1)F(n + 1).

  • Tiling a 2 × n board

    The last tile is one vertical domino or two horizontal ones: the same recurrence.

  • House robber

    Rob house ii plus best up to i−2i - 2, or skip it and take best up to i−1i - 1: 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.

Sources