Sub topic 6
Memoization and Tabulation Compared
Assume you know recursion, asymptotic notation, arrays, and basic dynamic programming terminology. This chapter compares two ways to evaluate the same dynamic programming recurrence.
Dynamic programming applies when a problem has:
- Optimal substructure, meaning an optimal solution uses optimal solutions to smaller subproblems.
- Overlapping subproblems, meaning the same smaller problems appear repeatedly.
Memoization and tabulation avoid recomputing those repeated subproblems.
Memoization: top-down computation
Memoization starts with the original problem and follows recursion. After computing a state, it stores the result in a cache. A later request for the same state returns the cached value.
For Fibonacci numbers:
\[ F(n) = F(n-1) + F(n-2) \]
with \(F(0)=0\) and \(F(1)=1\).
from functools import cache
@cache
def fibonacci_memo(n):
if n <= 1:
return n
return fibonacci_memo(n - 1) + fibonacci_memo(n - 2)
print(fibonacci_memo(10)) # 55Without the cache, the recursion tree has exponential size. With the cache, each state from 0 through \(n\) is computed once. The time complexity is \(O(n)\), and the cache uses \(O(n)\) space. The call stack also uses \(O(n)\) space in the worst case.
Memoization is useful when the recurrence is easiest to express recursively or when many possible states are unreachable. It computes only the states encountered from the requested starting state.
Tabulation: bottom-up computation
Tabulation stores results in a table and fills that table from the smallest states upward. It replaces recursion with an explicit evaluation order.
def fibonacci_tab(n):
if n <= 1:
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(fibonacci_tab(10)) # 55This version also takes \(O(n)\) time and \(O(n)\) space. It avoids recursion-depth limits. Because each state depends only on the previous two states, the table can be reduced to \(O(1)\) space.
Choosing between them
| Property | Memoization | Tabulation |
|---|---|---|
| Direction | Top-down | Bottom-up |
| Main mechanism | Recursion plus cache | Iteration plus table |
| States evaluated | Reachable states only | Usually every table state |
| Stack usage | May be large | None from recursion |
| Common risk | Recursion depth or missing base case | Incorrect fill order |
Both methods have the same recurrence and usually the same asymptotic time. The practical choice depends on the dependency structure, memory limits, and implementation clarity.
Exercise
A recurrence has 1,000 possible states, but a particular input reaches only 120 of them. Which method may avoid evaluating the other 880 states, and what additional risk does it introduce?
Show answer
Memoization may evaluate only the 120 reachable states. It introduces recursion-stack usage and can hit a recursion-depth limit.