Sub topic 10
Shrinking the Table to One Row
This chapter assumes you already know the 2D minimum-cost path solution from the earlier chapter, the row-by-row fill order, and Big-O notation for space. The goal here is to cut the table's memory from O(m·n) down to O(n) without changing the answer.
Why One Row Is Enough
Look at the minimum-cost recurrence again:
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
Each cell reads two values: the cell directly above, from row i-1, and the cell to its left, from row i. Rows i-2 and earlier are never read again. You can discard them once row i-1 is complete.
The rolling-array technique goes one step further. It uses a single list dp of length n that holds two rows at once:
- Positions
0..j-1already hold the new rowi. - Positions
j..n-1still hold the old rowi-1.
When you reach position j, dp[j] is the value from above, and dp[j-1] is the value from the left. That is exactly what the recurrence needs.
The Code
def min_path_sum(grid):
m, n = len(grid), len(grid[0])
dp = [float('inf')] * n
dp[0] = 0
for i in range(m):
dp[0] += grid[i][0]
for j in range(1, n):
dp[j] = min(dp[j], dp[j - 1]) + grid[i][j]
return dp[-1]
print(min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7The code handles the boundaries without any extra checks:
- Before row 0, every entry is
infexceptdp[0] = 0. In row 0 the "above" value is alwaysinf, sominpicks the left value. - Column 0 has no left neighbor. The line
dp[0] += grid[i][0]adds the current cell's cost to the value from above.
Running the example produces these rows:
| After row | dp |
|---|---|
| 0 | [1, 4, 5] |
| 1 | [2, 7, 6] |
| 2 | [6, 8, 7] |
Common Errors
Two more mistakes come up often:
- Diagonal dependencies. Some recurrences also read
dp[i-1][j-1], the above-left cell. Maximal square and edit distance are examples. By the time you computedp[j], the olddp[j-1]has already been overwritten. Before you overwritedp[j], save its old value in a variable such asprev, and use that saved value as the diagonal for the next cell. - Losing the route. A single row keeps only the costs. The full table is gone, so you cannot backtrack through it. If you need the actual path, keep the 2D table. The next chapter covers backtracking.
Choosing the Shorter Side
The space cost is O(length of the row). If m is much smaller than n, transpose the iteration: loop over columns on the outside and keep a column-sized list. That reduces memory to O(min(m, n)). Time stays at O(m·n) in every version.
Exercise
Rewrite uniquepathswith_obstacles (grid cells equal to 1 are blocked) using one list of length n. What value should a blocked cell write, and how should dp start?
Show answer
Start with dp = [0] * n and set dp[0] = 1. For each row i and each j from 0 to n-1: if grid[i][j] == 1, set dp[j] = 0; otherwise, if j > 0, do dp[j] += dp[j-1]. Return dp[-1]. A blocked cell writes 0, so no paths pass through it. For column 0 the value from above is simply kept unless the cell is blocked.
Exercise
A grid has 2 rows and 1,000,000 columns. How much memory does the rolling array use if you keep a row-sized list, and how can you do better?
Show answer
A row-sized list holds 1,000,000 entries. If you iterate column by column with a column-sized list instead, it holds only 2 entries, so memory is O(min(m, n)) = O(2). The time is O(m·n) either way.