Skip to content
LeetQuant
F7 Programming and Algorithms Foundations

F7 · Programming and Algorithms Foundations · Lesson 4 of 6

Recursion and Memoisation

How to write a correct recursion, read its recursion tree, collapse repeated work with functools caching, and convert to iteration when Python's recursion limit bites.

17 min

The recursive contract

A recursive function has two parts:

  1. Base cases that answer the smallest inputs directly.
  2. A recursive step that reduces the input to strictly smaller instances and combines their answers.

Reason about it by induction: assume the call on a smaller input returns the right answer, and check that the combination is then correct. Do not trace every call in your head. The two common bugs are a missing base case and a step that does not shrink the input, and both give infinite recursion.

Fast exponentiation shows the pattern, and why halving matters:

def fast_pow(x, n):
    if n == 0:
        return 1
    half = fast_pow(x, n // 2)        # one recursive call, half the size
    return half * half if n % 2 == 0 else half * half * x

print(fast_pow(3, 13))   # 1594323

The recursion depth is about log⁡2n\log_2 n with at most two multiplications per level, so it uses O(log⁡n)O(\log n) multiplications instead of n−1n - 1. Calling fast_pow(x, n // 2) twice instead of storing half would give T(n)=2T(n/2)+O(1)=O(n)T(n) = 2T(n/2) + O(1) = O(n) and throw the gain away.

Recursion trees and repeated work

The naive Fibonacci recursion makes two calls per level:

def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

The number of calls satisfies C(n)=1+C(n−1)+C(n−2)C(n) = 1 + C(n-1) + C(n-2) with C(0)=C(1)=1C(0) = C(1) = 1, whose solution is C(n)=2Fn+1−1C(n) = 2F_{n+1} - 1. For n=30n = 30 that is 2×1,346,269−1=2,692,5372 \times 1{,}346{,}269 - 1 = 2{,}692{,}537 calls to compute F30=832,040F_{30} = 832{,}040, growing like φn≈1.618n\varphi^n \approx 1.618^n.

Yet there are only 31 distinct subproblems, F0F_0 to F30F_{30}. The tree recomputes them exponentially often. When subproblems overlap like this, store each answer the first time it is computed: memoisation. The cost becomes

(number of distinct states)×(work per state, excluding recursive calls).\text{(number of distinct states)} \times \text{(work per state, excluding recursive calls)} .

functools.cache and lru_cache

from functools import lru_cache

@lru_cache(maxsize=None)      # functools.cache is the same thing
def fib_memo(n):
    return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)

print(fib_memo(90))            # 2880067194370816120
print(fib_memo.cache_info())   # CacheInfo(hits=88, misses=91, maxsize=None, currsize=91)

Each of the 91 values is computed once (91 misses), and the 88 hits are the second calls that are now free. Practical points:

  • Arguments become dictionary keys, so they must be hashable: pass a tuple, not a list (a list raises TypeError: unhashable type: 'list').
  • maxsize=None never evicts; a bounded maxsize evicts the least recently used entries.
  • The cache lives as long as the function. Call fib_memo.cache_clear() between unrelated inputs, and avoid decorating methods, where the cache holds references to self.

Worked example

ways to make change

How many ways are there to make 100 cents from coins of 1, 5, 10 and 25 cents, where order does not matter? Give the recursion, its complexity and an iterative version.

Show solution

Let ways(i, amount) count the ways using only COINS[i:]. Either use COINS[i] at least once more (stay at i, reduce the amount) or never use it again (move to i + 1). Fixing the order of coin types is what stops 5 + 1 and 1 + 5 being counted twice.

from functools import cache

COINS = (1, 5, 10, 25)

@cache
def ways(i, amount):
    if amount == 0:
        return 1
    if amount < 0 or i == len(COINS):
        return 0
    return ways(i, amount - COINS[i]) + ways(i + 1, amount)

print(ways(0, 100))   # 242

There are at most k(A+1)k(A + 1) states for kk coin types and amount AA, each doing O(1)O(1) work, so the time and memory are O(kA)O(kA); cache_info() reports 541 misses here. Without the cache the recursion revisits the same (i, amount) pairs many times over.

Bottom-up, process one coin type at a time and let w[a] count the ways to make a with the coins seen so far:

def ways_dp(amount, coins=COINS):
    w = [1] + [0] * amount
    for c in coins:
        for a in range(c, amount + 1):
            w[a] += w[a - c]
    return w[amount]

print(ways_dp(100))   # 242

Same O(kA)O(kA) time, O(A)O(A) memory and no recursion depth at all.

Python's recursion limit

CPython does not optimise tail calls and caps the stack depth: sys.getrecursionlimit() is 1000 by default, and exceeding it raises RecursionError. Memoisation does not help with depth. On an empty cache fib_memo(5000) still has to descend 5000 frames, and it raises RecursionError.

sys.setrecursionlimit raises the cap but not the underlying C stack, so very deep recursion can crash the interpreter outright. In an interview, mention the limit whenever the depth can grow with nn (linked structures, deep trees, DP over a long sequence) and offer an iterative version:

  • Bottom-up DP: fill the table in dependency order, as ways_dp did. For Fibonacci, keep the last two values: a, b = b, a + b.
  • An explicit stack: push what the call stack would have held. This is how you write deep DFS.

Worked example

flattening nested lists without recursion

Flatten arbitrarily nested lists, e.g. [1, [2, [3, 4]], 5, [[6]]] becomes [1, 2, 3, 4, 5, 6]. The natural recursion fails on a list nested 5000 deep. Write a version that does not.

Show solution

The recursive version is direct:

def flatten(xs):
    out = []
    for x in xs:
        if isinstance(x, list):
            out.extend(flatten(x))
        else:
            out.append(x)
    return out

Each nesting level costs one frame, so 5000 levels raise RecursionError. What does a suspended call remember? Only where it was in its own list. So keep a stack of iterators: descend by pushing a new iterator, and pop when one is exhausted.

def flatten_iter(xs):
    out, stack = [], [iter(xs)]
    while stack:
        for x in stack[-1]:          # resume the innermost list where it left off
            if isinstance(x, list):
                stack.append(iter(x))
                break                # descend into x
            out.append(x)
        else:                        # loop finished without break: list exhausted
            stack.pop()
    return out

print(flatten_iter([1, [2, [3, 4]], 5, [[6]]]))   # [1, 2, 3, 4, 5, 6]

The output order matches the recursion because the iterator on top of the stack is exactly the innermost active call. Time is O(total elements)O(\text{total elements}) and the stack is bounded by heap memory, not the recursion limit, so a list nested 5000 deep around 42 returns [42].

Knowledge check

How many calls in total does the naive recursive fib(5) make (including the top-level call), with base cases n < 2?

Knowledge check

You decorate def best(prices, i) with @functools.cache and call best([3, 1, 4], 0). What happens?

Knowledge check

With memoisation, what is the time complexity of counting the ways to make amount A from k coin types using ways(i, amount)?

Key takeaways

  • Write base cases first, make every call shrink the input, and reason by induction.
  • Overlapping subproblems make naive recursion exponential; memoise and the cost is states × work per state.
  • functools.cache needs hashable arguments; inspect it with cache_info().
  • Python has no tail-call optimisation and a default depth limit of 1000; caching does not raise it.
  • Convert deep recursion to bottom-up DP or an explicit stack, and say so before the interviewer asks.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).