Sub topic 8
Memoization or tabulation: making the choice
This chapter assumes you can already write a recurrence, implement it with functools.lru_cache, and turn it into a bottom-up table. It also assumes you can count states and the work done per state. Here the question is practical. You have a correct recurrence. Should you memoize it or tabulate it?
Both approaches compute the same values from the same recurrence. They differ in which states they visit, how deep the call stack gets, how much memory each stored value costs, and how much you must work out before writing code. Each of these factors can decide the choice, and each one is described below.
The decision at a glance
| Factor | Memoization (top-down) | Tabulation (bottom-up) |
|---|---|---|
| States computed | Only those reachable from the starting state | Every state in the table |
| Fill order | Found automatically by the recursion | You must choose a valid order |
| Stack depth | Grows with the longest dependency chain | Constant, because loops replace recursion |
| Memory per state | Dictionary entry, several times a list slot | List slot, or less with rolling arrays |
| Constant factor | Function call and hash lookup per access | Index arithmetic in a loop |
| Space reduction | Hard, because the cache keeps everything | Natural, by keeping only the rows you need |
| Ease of writing | Close to the recurrence as written | Needs extra thought about bounds and order |
Factor 1: state coverage
Tabulation fills every cell. Memoization computes only the states the recursion actually reaches from the top-level call. When the reachable states are a small part of the full state space, memoization wins by a huge margin.
Here is a classic case. A coin with value n can be exchanged for three coins worth n // 2, n // 3, and n // 4. Alternatively you can keep it as n. The goal is the best total you can get.
from functools import lru_cache
@lru_cache(maxsize=None)
def best(n):
if n == 0:
return 0
return max(n, best(n // 2) + best(n // 3) + best(n // 4))
print(best(10**12))
print(best.cache_info().currsize, "states computed")Each call divides n, so the only reachable values have the form n // (2**a * 3**b). There are only a few hundred of those. A table indexed from 0 to 10^12 would need a trillion entries, which is impossible to allocate. The recurrence is the same in both cases. Only memoization makes it workable.
The opposite case is also common. In Fibonacci, coin change, or longest common subsequence, the top-level call ends up touching nearly every state. Memoization then saves no work and still pays its overheads.
Factor 2: recursion depth
A memoized function recurses along the longest chain of dependencies before anything returns. For fib(n) that chain has length n. CPython's default recursion limit is 1000 frames, so a memoized solution that works on small tests can fail on real inputs.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
try:
fib(5000)
except RecursionError as e:
print("failed:", e)
# Warm the cache in steps so no single call recurses deeply.
fib.cache_clear()
for k in range(0, 5001, 200):
fib(k)
print(len(str(fib(5000))), "digits")The warm-up loop works because each call fib(k) only recurses until it reaches the value cached by the previous step, about 200 frames down. This trick works when you know the order in which states depend on each other. If you know that order, though, you have most of what you need to write a tabulation.
You can raise the limit with sys.setrecursionlimit, but that only changes Python's counter. The real stack belongs to the operating system thread. If the limit is set too high, the interpreter can crash with a segmentation fault and give no Python traceback at all.
Here is a rule of thumb. If the longest dependency chain grows linearly with the input, as in Fibonacci, edit distance, or most sequence DP, and inputs can reach the thousands, tabulate. If depth grows logarithmically, as in best above, recursion is safe.
Factor 3: memory and constant factors
The two approaches store results differently. Tabulation stores a value in a list slot, which is an 8-byte pointer on a 64-bit build. A memoization cache is a hash table. Each entry stores a key, a value, and a hash, and the table keeps spare capacity. The per-entry cost is several times higher. Each lookup also costs a function call and a hash computation, while each table read costs one index operation.
In practice, a tabulated loop in CPython often runs a few times faster than the equivalent memoized recursion when coverage is full. On small inputs that rarely matters. On a million states it can decide whether the code meets a time limit.
The larger memory difference comes from space optimization. A cache keeps every entry it has ever stored. A table filled in a known order lets you discard rows that no later state depends on, which a later chapter covers. Reducing a two-dimensional table to one row only works because tabulation fixes the order of computation. Memoization has no equivalent move.
Factor 4: how hard the fill order is
Tabulation requires an order in which each state is computed after all the states it depends on. For Fibonacci the order is plain: increasing n. For a grid it is row by row. Some recurrences are harder:
- Interval DP, where
dp[i][j]depends on shorter intervals inside[i, j], must be filled by increasing interval length, not byiand thenj. - Recurrences over several parameters can depend on states in more than one direction.
- Recurrences over states that are tuples, bitmasks, or strings may have no simple index ordering at all.
Memoization finds a valid order automatically, because the recursion asks for each dependency before it uses it. So memoization is often the faster way to get a first correct solution, even if you convert it later.
A practical workflow combines both approaches:
- Write the recurrence as a memoized function. It is short and mirrors the math.
- Test it on small inputs, ideally against brute force.
- If depth, speed, or memory becomes a problem, convert it to a table, and use the memoized version as a reference to test against.
from functools import lru_cache
def count_ways(n, steps):
"""Number of ways to climb n stairs using the given step sizes."""
steps = tuple(steps)
@lru_cache(maxsize=None)
def ways(k):
if k == 0:
return 1
return sum(ways(k - s) for s in steps if s <= k)
return ways(n)
def count_ways_table(n, steps):
dp = [0] * (n + 1)
dp[0] = 1
for k in range(1, n + 1):
dp[k] = sum(dp[k - s] for s in steps if s <= k)
return dp[n]
for n in range(30):
assert count_ways(n, [1, 3, 5]) == count_ways_table(n, [1, 3, 5])
print(count_ways_table(500, [1, 3, 5]) > 0)Common errors with `lru_cache`
Several mistakes come from how the cache is keyed and how long it lives, not from the recurrence itself.
- Unhashable arguments. Passing a list to a cached function raises
TypeError: unhashable type: 'list'. Convert it to a tuple, or keep it outside the cached function's arguments, ascount_waysdoes. - Stale caches across inputs. If a module-level cached function reads a global list, the cache does not know when that list changes. A second call with different data returns old answers. Define the cached function inside the outer function, as above, so each call gets a fresh cache.
- Caching too much state. Including an argument that does not affect the answer, such as a running counter or a debug flag, multiplies the number of keys and destroys the reuse you wanted.
- Bounded caches.
@lru_cachewithout arguments defaults tomaxsize=128. On a DP with thousands of states, it evicts entries you will need again, and the run time can quietly go back to exponential. Usemaxsize=None, orfunctools.cachein Python 3.9 and later. - Leaking memory. A module-level cache lives until the program ends. In a long-running service, call
cache_clear()or scope the cache to the request.
Choosing in practice
| Situation | Usual choice | Reason |
|---|---|---|
| Huge state space, few reachable states | Memoization | Tabulation would allocate states never used |
| Linear-depth chain, large `n` | Tabulation | Avoids `RecursionError` and stack crashes |
| Full coverage, tight time limit | Tabulation | Lower constant factor per state |
| Need to reduce memory to one or two rows | Tabulation | Requires a fixed fill order |
| Complex or unclear dependency order | Memoization | The recursion finds the order |
| Prototyping or checking a recurrence | Memoization | Closest to the math, fewest bugs |
When none of these factors applies, choose the version that is easier to read and review. Both have the same asymptotic complexity, so clarity is a valid tie-breaker.
Exercise
A recurrence over states (i, j) with 0 <= i, j < 5000 makes dp[i][j] depend on dp[i-1][j] and dp[i][j-1]. The answer is dp[4999][4999], and nearly every state is reachable. Which approach would you choose in CPython, and why?
Show answer
Tabulation. Coverage is full, so memoization saves no work. The dependency chain from (4999, 4999) to (0, 0) is about 10,000 calls deep, which exceeds the default recursion limit. The 25 million states would also cost far more memory as dictionary entries than as list slots. Tabulation fills the grid row by row with no recursion and can be reduced to a single row of 5000 values.
Exercise
A colleague's memoized function is fast in tests but takes minutes on production inputs with about 50,000 distinct states. It is decorated with plain @lru_cache. What is the likely cause and the fix?
Show answer
Plain @lrucache defaults to maxsize=128. With 50,000 states, entries are evicted and recomputed constantly, so much of the repeated work comes back. Use @lrucache(maxsize=None) or functools.cache so every state is stored once.
Exercise
Why does the best(n) coin-exchange function above work well with memoization but not tabulation, even though both use the same recurrence?
Show answer
The only reachable states are values n // (2a * 3b), and there are only a few hundred of those for n = 1012. Memoization computes only those states. A table indexed by every integer from 0 to n would need about 1012 entries, which cannot be allocated. Recursion depth is also only logarithmic in n, so the usual risk of memoization does not apply.