Sub topic 9
Memoization and tabulation compared
This chapter assumes you know what optimal substructure and overlapping subproblems mean, can read a recurrence, and are comfortable with Python recursion and lists. Both techniques here compute the same recurrence. They differ in the order they evaluate subproblems, the memory they use, and how they fail.
Two ways to evaluate one recurrence
Dynamic programming turns an exponential recursion into a polynomial one by solving each distinct subproblem once. There are two standard ways to do this.
- Memoization (top-down) is recursion plus a cache. You call the function on the full problem. Before computing a subproblem, you check whether its answer is stored. If it is, you return it. If not, you compute it, store it, and return it.
- Tabulation (bottom-up) is iteration over a table. You decide an order in which every subproblem's dependencies are already filled in, then fill the table from the base cases up to the answer.
The recurrence, the base cases, and the number of states are identical in both. Only the control flow differs.
The same problem both ways
The longest common subsequence (LCS) recurrence is: L(i, 0) = L(0, j) = 0. If a[i-1] == b[j-1], then L(i, j) = L(i-1, j-1) + 1. Otherwise L(i, j) = max(L(i-1, j), L(i, j-1)).
from functools import lru_cache
def lcs_memo(a, b):
@lru_cache(maxsize=None)
def f(i, j):
if i == 0 or j == 0:
return 0
if a[i - 1] == b[j - 1]:
return f(i - 1, j - 1) + 1
return max(f(i - 1, j), f(i, j - 1))
return f(len(a), len(b))
def lcs_table(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
print(lcs_memo('ABCBDAB', 'BDCABA')) # 4
print(lcs_table('ABCBDAB', 'BDCABA')) # 4Both versions visit at most (m+1)(n+1) states and spend O(1) work on each one. Both run in O(mn) time.
Dependency order decides the loop order
In tabulation you must choose the fill order yourself. Each cell must be computed after the cells it reads. For LCS, dp[i][j] reads the left, upper, and upper-left cells. Row-major order satisfies this. For matrix chain multiplication, m[i][j] depends on shorter chains, so you loop over chain length. A wrong loop order gives wrong answers silently, because you read cells that still hold their initial values.
Memoization finds the order for you. The recursion visits dependencies first, and the call stack enforces the order.
Space reduction works only with tabulation
If a cell reads only the previous row, you can keep two rows instead of the whole table.
def lcs_rows(a, b):
prev = [0] * (len(b) + 1)
for i in range(1, len(a) + 1):
cur = [0] * (len(b) + 1)
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
cur[j] = prev[j - 1] + 1
else:
cur[j] = max(prev[j], cur[j - 1])
prev = cur
return prev[-1]
print(lcs_rows('ABCBDAB', 'BDCABA')) # 4This uses O(n) space. The 0/1 knapsack chapter takes the same idea to a single row. The cost is that you can no longer reconstruct the actual subsequence from the table, because the older rows are gone. A memoized cache cannot drop entries safely, since you do not know which ones later calls will need.
Comparison
| Aspect | Memoization | Tabulation |
|---|---|---|
| Direction | Top-down, from the goal | Bottom-up, from base cases |
| Subproblems solved | Only those reachable from the goal | All table cells |
| Fill order | Automatic | You must derive it |
| Overhead | Function calls, hash lookups | Plain loops, array indexing |
| Stack depth | Up to the recursion depth | None |
| Space reduction | Hard | Often easy (rolling rows) |
| Time (worst case) | Same asymptotic bound | Same asymptotic bound |
When each one wins
Memoization wins when only a small part of the state space is reachable. In a knapsack with a very large capacity and a few items, most capacity values are never needed by any call. A table over every capacity does wasted work.
Tabulation wins when nearly every state is needed, which is true for LCS and edit distance. It avoids per-call overhead and lets you shrink memory.
Common errors
- Recursion limit. Python's default limit is about 1000 frames.
lcs_memoon strings of length 600 each can reach depth 1200 and raiseRecursionError. Use tabulation or raise the limit. - Forgetting the cache. Without it, the recursion is exponential. Each call to
f(i, j)with a mismatch spawns two calls, and the same subproblems are recomputed many times. - Mutable arguments.
lru_cacheneeds hashable arguments. Pass indices or tuples, not lists. - Wrong iteration direction. In 1D knapsack, looping capacities upward lets one item be used several times, which solves the unbounded problem instead.
Exercise
A memoized LCS function is called on strings of lengths m and n. State the number of distinct subproblems, the time complexity, the space used by the cache, and the maximum recursion depth. Then state which of these a two-row tabulated version improves.
Show answer
There are (m+1)(n+1) distinct subproblems, so time is O(mn) with O(1) work per state. The cache holds O(mn) entries, and the recursion depth is at most m+n. The two-row tabulated version reduces space to O(min(m, n)) if you keep the shorter string as the row, and it has no recursion depth. Time stays O(mn).
Exercise
A 1D knapsack loop is written as for c in range(w, capacity + 1) instead of running capacities downward. What problem does it now solve, and why?
Show answer
It solves the unbounded knapsack. Going upward, dp[c - w] has already been updated for the current item, so the item can be added again and again.