Sub topic 9
Top-Down Memoization vs Bottom-Up Tabulation
The earlier chapters solved grid problems by filling a table row by row. The same recurrence can also be written as a recursive function that caches its results. This chapter compares the two styles, shows how to convert one into the other, and covers the failures specific to each style.
This chapter assumes you can read Python recursion, know what a call stack is, and have already seen the unique-paths and minimum-cost recurrences from earlier chapters.
Two Ways to Evaluate One Recurrence
The unique-paths recurrence says the number of ways to reach cell (i, j) is the sum of the ways to reach (i - 1, j) and (i, j - 1). Cells in the first row or column have exactly one way.
Top-down memoization writes this recurrence as a recursive function. It starts at the goal and asks for whatever it needs. A cache stores each answer the first time it is computed, so a repeated request costs a lookup instead of a recomputation.
Bottom-up tabulation fills an array in an order where every dependency is ready before it is read. It starts at the base cases and works toward the goal.
from functools import lru_cache
def unique_paths_memo(m, n):
@lru_cache(maxsize=None)
def ways(i, j):
if i == 0 or j == 0:
return 1
return ways(i - 1, j) + ways(i, j - 1)
return ways(m - 1, n - 1)
def unique_paths_table(m, n):
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
print(unique_paths_memo(3, 7)) # 28
print(unique_paths_table(3, 7)) # 28Both versions compute the same set of values and give the same answer. They differ in who decides the evaluation order. In the memoized version the call stack decides. In the tabulated version you decide.
Why the Cache Matters
Without the cache, ways(i, j) calls ways(i - 1, j - 1) twice: once through the cell above and once through the cell to the left. The repeated calls multiply at every level, so the plain recursion makes a number of calls proportional to the answer itself, which grows exponentially. With the cache, each of the m * n states is computed once.
Translating Between the Two Styles
Each part of a memoized function maps directly onto a part of a table-based solution:
| Top-down element | Bottom-up element |
|---|---|
| Function parameters `(i, j)` | Table indices `dp[i][j]` |
| Early `return` for base cases | Initialized cells (first row, first column, padding) |
| Recursive call `ways(i - 1, j)` | Table read `dp[i - 1][j]` |
| Order the call stack happens to produce | Explicit loop order (a topological order of dependencies) |
| Cache hit | Reading an already-filled cell |
| Out-of-range guard, such as `if i < 0` | Boundary check or a padded row/column |
To convert top-down code to bottom-up, list every call the function makes, find a loop order in which all of those calls point to cells already filled, and replace the calls with reads. To convert in the other direction, turn each table read into a call and each initialized cell into an early return.
Where Top-Down Wins
Only reachable states are computed
Memoization evaluates only the states the goal actually depends on. Tabulation fills every cell whether it is needed or not. With obstacles, the difference can be large: if a wall cuts off part of the grid, recursion never enters it. If the goal cell is blocked, the function returns 0 on the first call.
from functools import lru_cache
def unique_paths_obstacles_memo(grid):
m, n = len(grid), len(grid[0])
@lru_cache(maxsize=None)
def ways(i, j):
if i < 0 or j < 0 or grid[i][j] == 1:
return 0
if i == 0 and j == 0:
return 1
return ways(i - 1, j) + ways(i, j - 1)
return ways(m - 1, n - 1)
print(unique_paths_obstacles_memo([[0, 0, 0], [0, 1, 0], [0, 0, 0]])) # 2The i < 0 or j < 0 guard has to come before grid[i][j]. In Python, grid[-1] does not raise an error. It quietly reads the last row, which gives wrong answers with no warning.
No fill order to work out
With right/down moves, row-major order is obvious. When the dependencies follow some other pattern, such as moves in all four directions restricted by a value rule, there may be no simple loop order. Memoized recursion finds a valid order automatically, provided the dependencies contain no cycles. A later chapter on longest increasing paths depends on this.
The code stays close to the recurrence
The function body reads like the mathematical definition. This makes a first correct version quicker to write and easier to check.
Where Bottom-Up Wins
No recursion limit
CPython limits recursion depth to about 1000 frames by default. In the unique-paths function, recursion goes down one axis and then along the other, so the depth reaches roughly m + n frames.
from functools import lru_cache
def unique_paths_memo(m, n):
@lru_cache(maxsize=None)
def ways(i, j):
if i == 0 or j == 0:
return 1
return ways(i - 1, j) + ways(i, j - 1)
return ways(m - 1, n - 1)
try:
print(unique_paths_memo(800, 800))
except RecursionError:
print("RecursionError: the call stack got too deep")The tabulated version handles an 800 × 800 grid without trouble. Raising sys.setrecursionlimit can work, but a deep enough stack can crash the interpreter outright instead of raising a catchable error. Treat that setting as a last resort.
A middle option keeps the memoized function but warms its cache in dependency order, so each call finds its inputs already cached and the stack never gets more than a couple of frames deep:
from functools import lru_cache
def unique_paths_warmed(m, n):
@lru_cache(maxsize=None)
def ways(i, j):
if i == 0 or j == 0:
return 1
return ways(i - 1, j) + ways(i, j - 1)
for i in range(m):
for j in range(n):
ways(i, j)
return ways(m - 1, n - 1)
print(unique_paths_warmed(3, 7)) # 28
print(unique_paths_warmed(800, 800) > 0) # TrueOnce you have written that loop, you have already worked out the fill order, so a plain table is usually the cleaner choice.
Lower constant factors
Each memoized step pays for a Python function call and a hash lookup on the argument tuple. A table read is a list index. Both styles run in O(m · n) time, but tabulation is usually several times faster in Python.
Room for space optimization
When the loop order is explicit, you can see that row i reads only row i - 1, and you can keep a single row instead of the full table. The next chapter does exactly this. A memoization cache cannot shrink this way, because it keeps every state it has ever computed.
Common Errors with Caches
Default `lru_cache` size
Writing @lru_cache without arguments sets maxsize=128. For a grid with more than 128 states, entries get evicted and recomputed, and the running time can become exponential again. Use @lru_cache(maxsize=None) or functools.cache.
Unhashable arguments
Passing the grid itself to a cached function, as in ways(grid, i, j), raises TypeError: unhashable type: 'list'. Keep the grid in an enclosing scope and cache only the state parameters.
Stale caches across inputs
A cached function defined at module level keeps its cache between calls. If it reads a grid from outside its own arguments, changing that grid does not invalidate the cache:
from functools import lru_cache
GRID = [[0, 0], [0, 0]]
@lru_cache(maxsize=None)
def ways(i, j):
if i < 0 or j < 0 or GRID[i][j] == 1:
return 0
if i == 0 and j == 0:
return 1
return ways(i - 1, j) + ways(i, j - 1)
print(ways(1, 1)) # 2
GRID = [[0, 1], [0, 0]]
print(ways(1, 1)) # 2, a stale cached answer; the correct value is 1
ways.cache_clear()
print(ways(1, 1)) # 1Defining the cached function inside the solver, as the earlier examples do, gives each input a new cache and avoids this bug.
Choosing Between Them
| Situation | Prefer |
|---|---|
| Fill order is obvious (right/down moves) and the grid is large | Bottom-up |
| You plan to cut memory to one row | Bottom-up |
| Many states are unreachable or pruned | Top-down |
| Dependencies are acyclic but follow no simple loop order | Top-down |
| Prototyping or checking a recurrence | Top-down |
| Grid dimensions sum to more than about 1000 | Bottom-up, or top-down with a warmed cache |
Exercise
Rewrite the minimum path sum problem (moves right or down, minimize the sum of cell values) as a memoized function cost(i, j). What should it return when i or j is negative, and why?
Show answer
Return float('inf') for negative indices so that min() never picks an out-of-range predecessor. Return grid[0][0] at (0, 0). Otherwise return grid[i][j] + min(cost(i - 1, j), cost(i, j - 1)), decorated with @lru_cache(maxsize=None) and defined inside the solver.
Exercise
A memoized unique-paths solution uses @lru_cache with no arguments. It is fast on a 5 × 5 grid but extremely slow on a 30 × 30 grid. Explain the cause.
Show answer
Without arguments, lru_cache defaults to maxsize=128. A 30 × 30 grid has 900 states, so cached entries are evicted and recomputed, and the overlapping subproblems blow up again. Use maxsize=None or functools.cache.
Exercise
Why is the recursion depth of the memoized unique-paths function about m + n rather than m n, even though it computes m n states?
Show answer
Each call moves one step up or left, so any chain of calls toward a base case has at most (m - 1) + (n - 1) steps. Cached states return immediately and add no further depth.