Sub topic 5
Top-down DP with memoization
This chapter assumes you can write recursive Python functions, use dictionaries, and read Big-O notation. It also assumes you have a recurrence from the previous chapter: a state, a rule that builds each state from smaller ones, and base cases. Memoization is the most direct way to run that recurrence fast. You write the recursion as you would on paper, then add a cache so each state is computed once.
The core idea
A memoized function keeps a lookup table, usually a dictionary, that maps each state to its answer. Every call does the same three things:
- If the state is a base case, return the base value.
- If the state is already in the cache, return the stored value.
- Otherwise, compute the value from the recurrence, store it, and return it.
The recursion itself does not change. The only difference is that repeated calls become dictionary lookups instead of whole subtrees of work.
def fib(n, memo=None):
if memo is None:
memo = {}
if n < 2:
return n
if n not in memo:
memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
return memo[n]
print(fib(30)) # 832040
print(fib(90)) # 2880067194370816120Naive recursive fib(30) makes 2,692,537 calls. The memoized version computes each of the 31 states from 0 to 30 once, so it makes about 2n calls in total. fib(90) comes back at once. The naive version would take years.
What the call tree looks like now
The first call into a state does the real work. Every later call into that state stops at the cache check. The result is a single path down the left side of the tree, plus one cache hit at each level.
The order in which states get filled is decided by the recursion. You never had to work out which state must be computed before which. This is the main convenience of top-down DP, and it is why memoization is usually the fastest way to get a correct solution from a fresh recurrence.
Three ways to hold the cache
An explicit dictionary passed down
The version above passes memo as a parameter. It makes the cache visible, which helps when you are debugging or want to inspect the cache afterward.
The memo=None default followed by memo = {} is deliberate. Writing def fib(n, memo={}) creates one dictionary when the function is defined, and every call that omits memo shares it. For fib the shared cache happens to give correct answers. For any function whose answer also depends on data that is not in the key, a stale entry from an earlier call will silently return a wrong result.
A closure over the problem data
Many problems have fixed input data, such as a grid, a string, or a list of coins, plus a small changing state. Put the data in an outer function and memoize an inner function that takes only the state:
def unique_paths(grid):
"""Count right/down paths from top-left to bottom-right, avoiding 1-cells."""
rows, cols = len(grid), len(grid[0])
memo = {}
def paths(r, c):
if r < 0 or c < 0 or grid[r][c] == 1:
return 0
if r == 0 and c == 0:
return 1
if (r, c) not in memo:
memo[(r, c)] = paths(r - 1, c) + paths(r, c - 1)
return memo[(r, c)]
return paths(rows - 1, cols - 1)
grid = [
[0, 0, 0],
[0, 1, 0],
[0, 0, 0],
]
print(unique_paths(grid)) # 2The cache key is the tuple (r, c), which is exactly the DP state. Each call to unique_paths builds a fresh memo, so results from one grid can never leak into another. This pattern is the safest default.
`functools.lru_cache` and `functools.cache`
The standard library can do the bookkeeping for you. lru_cache(maxsize=None) wraps a function in an unbounded cache keyed on its arguments:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(30)) # 832040
print(fib.cache_info()) # CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)
fib.cache_clear()Since Python 3.9, functools.cache is an alias for lru_cache(maxsize=None). The cache_info() numbers show what memoization is doing: 31 misses, one per distinct state, and 28 hits, one for each fib(n - 2) call that found its answer already stored.
Leave maxsize as None for DP. A bounded LRU cache evicts old entries. A DP recursion may need those entries again, and then it recomputes them, which can bring back the exponential blowup you were trying to remove.
The decorator works well together with the closure pattern:
from functools import cache
def unique_paths(grid):
rows, cols = len(grid), len(grid[0])
@cache
def paths(r, c):
if r < 0 or c < 0 or grid[r][c] == 1:
return 0
if r == 0 and c == 0:
return 1
return paths(r - 1, c) + paths(r, c - 1)
return paths(rows - 1, cols - 1)
print(unique_paths([[0, 0], [0, 0]])) # 2A new paths function and a new cache are created on each call to unique_paths. When that call returns, they are freed.
Choosing between the approaches
| Approach | Strengths | Weaknesses |
|---|---|---|
| Explicit `memo` dict | Cache is easy to inspect. Works with any key you build. | More lines to write. Easy to forget the store or the check. |
| Closure with a dict | Fixed data stays out of the key. Fresh cache per problem. | Slightly more nesting. |
| `@cache` / `@lru_cache(maxsize=None)` | Least code. Includes `cache_info()` and `cache_clear()`. | All arguments must be hashable. A module-level cache lives until cleared. |
Common errors
Checking the cache after recursing
The cache check must come before the recursive calls. This version stores results but never benefits from them:
def fib_wrong(n, memo=None):
if memo is None:
memo = {}
if n < 2:
return n
result = fib_wrong(n - 1, memo) + fib_wrong(n - 2, memo) # always recurses
memo[n] = result
return resultIt still runs in exponential time. When you add memoization by hand, read the function from the top and confirm that a lookup happens before any recursive call.
Unhashable arguments
lru_cache builds its key from the arguments, so every argument must be hashable. Passing a list fails:
from functools import cache
@cache
def total(items):
return sum(items)
try:
total([1, 2, 3])
except TypeError as e:
print(e) # unhashable type: 'list'You can fix this in two ways. Pass a tuple or frozenset instead, or move the data into a closure and pass only small, hashable state such as indices. The second fix is usually better. Hashing a long tuple on every call costs O(length) per call, which adds a hidden factor to your running time.
Keys that leave out part of the state
The cache key must contain everything the answer depends on. Suppose a function's result depends on i and on a remaining budget k, but you cache only on i. Then the first k seen for each i decides the answer for every later k. The fix is to make the key match the state you defined: memo[(i, k)]. If you find yourself reading a non-constant global or an outer variable that changes during the recursion, that variable belongs in the key.
Caching a mutable result
If the memoized function returns a list or dictionary, every caller gets the same object. A caller that changes it corrupts the cache. Return tuples, or copy before you change anything.
Decorating methods
Putting @lru_cache on an instance method makes self part of the key. The cache then holds a reference to every instance it has seen, so those objects are never freed, and two equal instances may share entries. Use a closure inside the method, or a per-instance dictionary, instead.
Recursion depth
Memoization removes repeated work, but it does not remove recursion. The first call to fib(n) still descends through fib(n-1), fib(n-2), and so on, about n frames deep. CPython's default recursion limit is 1000:
from functools import cache
@cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
try:
fib(5000)
except RecursionError:
print("too deep")You have three options:
- Raise the limit with
sys.setrecursionlimit(10_000). This is fine for moderate depths. Very deep recursion can still crash the interpreter by overflowing the C stack, which no Python exception will catch. - Warm the cache in increasing order. Calling
fib(i)foriinrange(0, n + 1, 500)keeps every call shallow, because the earlier answers are already cached. - Switch to tabulation, which the next chapter covers. It needs no recursion at all.
from functools import cache
@cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
for i in range(0, 5001, 500):
fib(i)
print(len(str(fib(5000)))) # 1045 digitsWhere memoization shines
Top-down DP computes only the states that are actually reachable from the starting call. When the recurrence skips most of the state space, the savings are real. Examples include branches cut off by obstacles, or jumps such as n // 2 and n // 3 that touch only O(log² n) of the values below n. A table would fill every state. The memoized recursion fills only the ones it needs.
from functools import cache
@cache
def min_steps(n):
"""Fewest steps to reach 1 using n-1, n/2 (if even), n/3 (if divisible)."""
if n == 1:
return 0
best = min_steps(n - 1) + 1 if n <= 1000 else float('inf')
if n % 2 == 0:
best = min(best, min_steps(n // 2) + 1)
if n % 3 == 0:
best = min(best, min_steps(n // 3) + 1)
return best
print(min_steps(10)) # 3 (10 -> 9 -> 3 -> 1)The n <= 1000 guard is only there to keep the demo within the recursion limit. It shows a real limitation: a -1 step makes the recursion depth linear in n. The trade-offs between reachable states, depth, and memory are the subject of the chapter on choosing between memoization and tabulation.
Exercise
A function count(i, k) returns the number of ways to pick k items from items[i:] under some rule. A teammate memoizes it with memo[i] = result. On small tests it is correct, but on larger inputs it returns wrong answers. What is the bug, and how do you fix it?
Show answer
The cache key leaves out k, which is part of the state. The first value of k computed for a given i is returned for every later k at that i. The small tests probably only reached each i with a single k. Fix it by keying on the full state: store and look up memo[(i, k)], or decorate count with @cache so both arguments form the key.
Exercise
You decorate def solve(nums, i) with @lru_cache(maxsize=None) and call solve([3, 1, 4], 0). What happens, and what is the best fix?
Show answer
It raises TypeError: unhashable type: 'list', because lru_cache hashes every argument. Converting nums to a tuple works, but each call then pays O(len(nums)) to hash it. The better fix is to put nums in an enclosing function and memoize an inner function that takes only the index i, so the key is a single small integer.
Exercise
After calling a memoized fib(40) decorated with @cache on a fresh cache, how many misses and hits does cache_info() report? Explain the counts.
Show answer
misses=41 and hits=39. There is one miss for each distinct state from 0 to 40. Each fib(n) for n from 3 to 40 calls fib(n-1) first, which fills in fib(n-2), so its own call to fib(n-2) is a hit. That gives 38 hits. The call to fib(1) inside fib(2) is a miss, but the call to fib(1) inside fib(3) is a hit, and it is already counted among those 38. Checking another way: fib(n) for n from 2 to 40 makes 39 recursive pairs, or 78 calls, plus the top-level call, for 79 calls in total. Subtracting 41 misses leaves 38 hits. The correct answer is misses=41, hits=38. This matches the fib(30) case, which gives 31 misses and 28 hits.