Sub topic 12
Memoization and the space cost of dynamic programming
This chapter assumes you know Big O notation for time, can read recursive Python, and have seen how recursion uses call stack space. Memoization speeds up a function by storing results it has already computed. That speed costs memory, and this chapter shows how much.
What memoization does
Memoization means caching a function's return value, keyed by its arguments. A repeated call with the same arguments returns the stored value instead of recomputing it.
Plain recursive Fibonacci recomputes the same subproblems many times, so it takes exponential time. Caching fixes that.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
print(fib_memo(30))The time drops to O(n), because each value from 0 to n is computed once. The space is now O(n) for two separate reasons:
- The cache holds n + 1 results.
- The first call descends to depth n before any value is cached, so the call stack also grows to O(n).
Without the cache, the plain version uses only O(n) stack space. It is slow but not larger in space. Memoization adds the cache on top of the same stack depth. The two costs are both O(n) here, so they do not add up to a worse Big O.
The trade-off in one picture
Reducing the space of dynamic programming
Dynamic programming (DP) solves a problem by building answers to small subproblems and combining them. Memoization is the top-down form. The bottom-up form fills a table in order.
A bottom-up table often keeps more than it needs. Fibonacci at step i depends only on the two previous values, so you can discard everything older.
def fib_iter(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib_iter(30))This runs in O(n) time and O(1) auxiliary space. It also removes the recursion, so there is no stack growth and no depth limit.
The same idea applies to larger tables. If row i of a 2D table depends only on row i - 1, keep two rows instead of all of them. A table of n × m cells uses O(n·m) space. Two rolling rows of length m use O(m).
| Approach | Time | Space |
|---|---|---|
| Plain recursion | O(2^n) | O(n) stack |
| Memoized recursion | O(n) | O(n) cache + O(n) stack |
| Bottom-up table | O(n) | O(n) table |
| Rolling variables | O(n) | O(1) |
Common errors
- Forgetting the stack. Calling a memoized function "O(n) cache only" ignores the recursion depth. For large n, Python raises
RecursionErrorat its default limit of about 1000 frames, even when memory is plentiful. - Unhashable arguments.
lru_cacheneeds hashable arguments. Passing a list raisesTypeError. Convert it to a tuple first. - Counting only the final answer. The cache stores every subproblem, not just the one you return.
- Shrinking space when you need the path. Rolling variables keep only values, not the choices that led to them. If you must reconstruct the solution, you need to keep more information.
Exercise
A DP solution fills an n × n table where each row depends only on the row above it. What is the auxiliary space of the full-table version, and what is it if you keep only two rows? Name one thing you lose by keeping only two rows.
Show answer
The full table uses O(n²) space. Two rolling rows use O(n). You lose the earlier rows, so you can no longer trace back through them to reconstruct which choices produced the final answer.
Exercise
Why does fib_memo(5000) fail with a RecursionError even though a cache of 5001 integers is tiny?
Show answer
The first call recurses to depth about 5000 before any result is cached. That exceeds Python's default recursion limit of about 1000 frames, so the call stack is the limit, not the heap memory used by the cache. Calling fib_memo with increasing values first, or using fib_iter, avoids it.