Sub topic 8
Memoization or tabulation: making the choice
This chapter assumes you can already write a recurrence both ways: top-down with a dictionary or functools.lru_cache, and bottom-up with a table. It also assumes you can count states and work per state. The question here is which version to write for a given problem.
Both versions compute the same values from the same recurrence, and their worst-case Big-O time is usually identical. They differ in three practical ways: which states get computed, how deep the call stack grows, and how much memory you can save.
State coverage: which states actually get computed
Memoization computes only the states that the original call actually reaches. Tabulation computes every cell in the table, whether the final answer needs it or not.
For Fibonacci, every state from 0 to n is needed, so the two versions do the same work. Some recurrences jump around and touch only a small fraction of the possible states. Here is one:
from functools import lru_cache
@lru_cache(maxsize=None)
def f(n):
if n == 0:
return 1
return f(n // 2) + f(n // 3)
print(f(10**12))
print(f.cache_info().currsize) # number of distinct states actually computedThe cache ends up holding a few thousand entries. A bottom-up table would need 10^12 cells, which is not feasible. When the reachable states are sparse, or you can't easily list them in advance, memoization is the natural choice.
Recursion depth: the stack limit
Memoized code is recursive, so the longest chain of calls becomes the stack depth. CPython's default recursion limit is 1000, and a long dependency chain will exceed it:
import sys
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)
def fib_table(n):
if n < 2:
return n
table = [0] * (n + 1)
table[1] = 1
for i in range(2, n + 1):
table[i] = table[i - 1] + table[i - 2]
return table[n]
print(sys.getrecursionlimit())
try:
fib_memo(5000)
except RecursionError:
print("memo: RecursionError")
print(len(str(fib_table(5000)))) # 1045 digits, no recursion involvedA common workaround keeps the memoized function and warms its cache in increasing order, for example by calling fib_memo(i) for i in range(n). At that point you are filling a table by hand, so writing the loop directly is usually cleaner.
Memory and constant factors
Tabulation makes the fill order explicit, and that is what lets you shrink memory. If row i depends only on row i - 1, you keep two rows instead of the whole table. A memo dictionary gives you no such control, because it keeps every entry until you clear it.
Memoization also has more overhead per state. Each state costs a function call, hashing the arguments, and a dictionary entry. A list index is cheaper. The Big-O is the same either way, but a tight bottom-up loop is often several times faster in Python.
Memoization's advantage is that it is easier to get right. You write the recurrence as it reads, and the recursion handles the order for you. With tabulation you must pick a fill order in which every dependency is computed before it is used. In two-dimensional or irregular state spaces, choosing that order is a common source of bugs.
Side-by-side summary
| Factor | Memoization | Tabulation |
|---|---|---|
| States computed | Only those reached | All cells in the table |
| Fill order | Handled by recursion | You must choose a valid one |
| Recursion depth | Can hit the stack limit | None |
| Space optimization | Hard | Easy with rolling rows |
| Per-state overhead | Function call plus hashing | List indexing |
| Ease of writing | Close to the recurrence | Needs more planning |
A common workflow is to prototype with lru_cache to confirm the recurrence is correct, then convert to a table once you need more speed, a deeper input, or less memory.
Exercise
You need the number of ways to climb n = 100000 stairs taking 1 or 2 steps at a time, modulo 10^9 + 7. Which implementation do you choose, and why?
Show answer
Tabulation, ideally with two rolling variables. Every state from 0 to n is needed, so memoization saves no work. Its recursion depth would reach about 100000, far past Python's default limit of 1000. Because each state depends only on the previous two, a bottom-up loop uses O(1) space.
Exercise
A recurrence over (i, j) with 0 <= i, j <= 10^6 is called once from (10^6, 10^6), and each call moves to (i // 2, j - 1) or (i - 1, j // 3). Which approach fits better?
Show answer
Memoization. The full table would have about 10^12 cells. The halving and thirding moves shrink the coordinates quickly, so only a small fraction of states is ever reached. Check the recursion depth before you rely on it, though. Each move cuts one coordinate quickly but lowers the other by only 1, so a path that keeps alternating could chain many calls in a row.