Sub topic 3
Top-Down Memoization vs Bottom-Up Tabulation
This chapter assumes you know the cell state, the recurrence, and the fill order from the earlier chapters. It also assumes you are comfortable with recursion and Big-O notation.
Top-Down Memoization vs Bottom-Up Tabulation
Both styles compute the same recurrence. Top-down code recurses from the goal and caches each (i, j), for example with lru_cache. It only visits the states it needs, but deep grids can exceed Python's recursion limit. Bottom-up code fills a table in an order you choose. It has no call-stack risk and makes later memory savings possible.
| Style | Order chosen by | Main risk |
|---|---|---|
| Memoization | the recursion | stack depth |
| Tabulation | you | wrong fill order |
Shrinking the Table to One Row
If cell (i, j) reads only from row i - 1 and from row i, a single array is enough. Before you overwrite dp[j], it still holds the value from the row above. dp[j - 1] already holds the new value to its left.
def min_path_sum(grid):
n = len(grid[0])
dp = [float('inf')] * n
dp[0] = 0
for row in grid:
dp[0] += row[0]
for j in range(1, n):
dp[j] = min(dp[j], dp[j - 1]) + row[j]
return dp[-1]
print(min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7Space drops from O(mn) to O(n).
Recovering the Optimal Path
To output the route, keep the full 2D table. Start at the goal and step to whichever predecessor has the smaller cost. Then reverse the list of cells. A one-row table can't do this, because the earlier rows have been overwritten.
Maximal Square of Ones
dp[i][j] is the side length of the largest all-ones square whose bottom-right corner is at (i, j). If the cell holds a 1, its value is 1 + min(up, left, diagonal). Adding a padding row and column of zeros removes the edge checks.
Edit Distance: When Two Strings Form a Grid
Rows are prefixes of a and columns are prefixes of b. A move up is a deletion, a move left is an insertion, and a diagonal move is a substitution, or a free match when the characters are equal. Row 0 holds j and column 0 holds i.
Working Backward from the Goal
In the dungeon game, the health you need when entering a cell depends on the cells still ahead. So you fill the table from the bottom-right corner back to the start, using max(1, min(down, right) - cell).
Longest Increasing Path: Memoized DFS over a DAG
When moves can go in all four directions, no row-by-row fill order works. Because each step must go to a strictly larger value, the dependencies can't form a cycle. Memoized DFS therefore computes each cell once, which takes O(mn) time.
Two Walkers at Once: Cherry Pickup
Model two walkers who move at the same time. The state is (r1, c1, r2), and c2 = r1 + c1 - r2 because both walkers have taken the same number of steps. If both walkers stand on the same cell, count its cherry once. There are O(n³) states with 4 transitions each.
Exercise
What is the edit distance between "cat" and "cut", and which grid move achieves it?
Show answer
The distance is 1. One diagonal substitution turns 'a' into 'u', and the other characters match through free diagonal moves.
Exercise
Why can't the one-row minpathsum be used to reconstruct the route?
Show answer
Each row overwrites the one before it, so the costs of earlier rows that backtracking needs are no longer stored.