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.

See it run

Watch one line of recursion branch into a tree that redoes the same calls, then cut it down with a memo and flatten it into a loop.

Operations

Naive call tree: fib(5)

Run fib(5) with fib(n) = fib(n - 1) + fib(n - 2) and draw every call. Each call above the base cases makes two more, so the calls form a tree, and the same subtrees appear again and again.

Step 1 of 10

One call, two base cases, one rule

fib(5)call 1

calls so far: 1

fib(0) = 0 and fib(1) = 1 are the base cases: they return at once. Every other call returns fib(n - 1) + fib(n - 2). We start with fib(5) and count every call we make.

Step 1: One call, two base cases, one rule

def fib(n):    if n <= 1:            # base cases: fib(0) = 0, fib(1) = 1        return n    left = fib(n - 1)     # first call runs all the way down before the second starts    right = fib(n - 2)    # second call: often a repeat of work already done    return left + right
Time
O(2ⁿ), exactly Θ(φⁿ)
Space
O(n) call stack
fib(5)
15 calls
fib(20)
21,891 calls
fib(40)
331,160,281 calls

Draw the tree for fib(5) once and circle the repeated labels. If you can see the same call twice, a cache will help.

In the real world

The same recursion: fibonacci doing real jobs. Pick one and step through it.

The puzzle Fibonacci posed in 1202: a pair of rabbits that breeds every month once it is two months old. Count the pairs month by month and the Fibonacci numbers appear.

Step 1 of 7

Month 0: an empty field

01234567
adult0·······
young0·······
total0·······

month 0: 0 pairs

Month 0: the field is empty. 0 pairs, our fib(0) = 0.

Step 1: Month 0: an empty field

adult, young = 0, 1          # month 1for month in range(2, 8):    adult, young = adult + young, adult    print(month, adult + young)  # 1, 2, 3, 5, 8, 13

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Only one base case

    critical

    With only n == 1 handled, fib(2) calls fib(0), which calls fib(-1), fib(-2) and so on forever, until RecursionError. Both fib(0) = 0 and fib(1) = 1 must stop the recursion; n <= 1 covers both.

    Wrong
    def fib(n):    if n == 1:        return 1    return fib(n - 1) + fib(n - 2)   # fib(2) -> fib(0) -> fib(-1) ...
    Right
    def fib(n):    if n <= 1:        return n                      # fib(0) = 0 and fib(1) = 1    return fib(n - 1) + fib(n - 2)
  • Calling fib(n - 1) twice

    critical

    fib(n - 1) + fib(n - 1) computes 2 · F(n - 1), not F(n), and it doubles the calls exactly, so it is wrong and also a true O(2ⁿ). The second call must be n - 2.

    Wrong
    return fib(n - 1) + fib(n - 1)   # fib(2) gives 2 and fib(3) gives 4: wrong
    Right
    return fib(n - 1) + fib(n - 2)   # the two previous terms
  • A mutable default argument as the memo

    major

    def fib(n, memo={}) creates the dictionary once, when the function is defined, and every later call shares it. It happens to give right answers for Fibonacci, but the cache grows forever and the same pattern silently breaks functions whose answers depend on other inputs.

    Wrong
    def fib(n, memo={}):          # one dict shared by every call, ever    if n in memo:        return memo[n]    ...
    Right
    def fib(n, memo=None):    if memo is None:        memo = {}                 # fresh dict per top-level call    ...# or simply: @functools.cache on the plain recursive version
  • Naive recursion for a large n

    major

    fib(40) makes 331 million calls and fib(50) about 40 billion. If n can be more than about 30, cache the results or use a loop.

    Wrong
    print(fib(50))       # naive: effectively never finishes
    Right
    from functools import cache@cachedef fib(n):    return n if n <= 1 else fib(n - 1) + fib(n - 2)print(fib(50))       # 12586269025, instantly
  • Memoised but still too deep

    minor

    A cache fixes the time, not the depth. The first call still recurses n frames down, so fib(5000) raises RecursionError under Python's default limit of about 1,000. Raising the limit risks crashing the interpreter; a loop needs no stack.

    Wrong
    fib_memo(5000)                    # RecursionError: maximum recursion depth exceeded
    Right
    def fib(n):    a, b = 0, 1    for _ in range(n):        a, b = b, a + b    return a                      # O(n) time, O(1) space, no recursion
  • Off by one in the indexing

    minor

    Some texts start the sequence at F(1) = F(2) = 1. If a problem says the first term is 1 and you assume F(0) = 0, every answer shifts by one place. Check the problem's first two terms before coding.

    Wrong
    # problem: "terms 1 and 2 are both 1; return term n"def term(n):    a, b = 0, 1    for _ in range(n - 1):        # quietly treats term 1 as F(0) = 0        a, b = b, a + b    return a                      # term(6) gives 5, expected 8
    Right
    def term(n):    a, b = 0, 1    for _ in range(n):            # term n is F(n): term(1) = term(2) = 1        a, b = b, a + b    return a                      # term(6) = 8

Interview tips

  • How to explain it

    • Naive recursion makes two calls per call, so the calls form a tree with about φⁿ nodes: O(2ⁿ) as an upper bound.
    • There are only n + 1 distinct subproblems, so the tree is full of repeats: overlapping subproblems.
    • Memoise (top-down) or tabulate (bottom-up) and the time drops to O(n); two variables bring space to O(1).
  • Spot it in problems

    • The answer for n depends on the answers for n - 1 and n - 2: climbing stairs, tiling a 2 × n board, house robber.
    • A recursive solution whose call tree repeats the same arguments.
    • Counting ways where the last move was one of two kinds.
  • Memory tricks

    • FIBR: First check base cases, If not then recurse, Break into n - 1 and n - 2, Return the sum.
    • Rabbits: this month's pairs = last month's pairs + the month before's.
    • 0, 1, 1, 2, 3, 5, 8, 13, 21, 34: say it once a day and F(10) = 55 stays with you.
  • Watch out

    • Both base cases, fib(0) and fib(1), or the recursion runs off below zero.
    • Never use a mutable default argument as the memo.
    • Memoised recursion is still n deep: use a loop for very large n.
    • Fibonacci numbers get big fast; problems often ask for the answer modulo 10⁹ + 7.