Sub topic 10
Shrinking the Table to One Row
This chapter assumes you can already write the full 2D table for unique paths and minimum path sum. You should know why each cell reads from the cell above and the cell to its left, and you should be comfortable with Big-O notation for space. The goal is to keep the same recurrence and the same answer while storing far less of the table.
Why Most of the Table Is Dead Weight
Take the minimum-cost recurrence again:
# dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]To fill row i, you only read row i - 1 and the part of row i already filled. Rows 0 through i - 2 are never read again. A 2D table of m × n entries therefore keeps about (m - 2) × n values that no later step will touch.
This gives a general rule. If a cell's dependencies all lie in the current row or the row directly above, you only need to keep those two rows. With careful update order, one row is enough.
Step One: Two Rows
The simplest safe reduction keeps a prev row and a cur row. When cur is finished it becomes prev for the next row.
def min_path_sum_two_rows(grid):
m, n = len(grid), len(grid[0])
prev = [0] * n
prev[0] = grid[0][0]
for j in range(1, n):
prev[j] = prev[j - 1] + grid[0][j]
for i in range(1, m):
cur = [0] * n
cur[0] = prev[0] + grid[i][0]
for j in range(1, n):
cur[j] = min(prev[j], cur[j - 1]) + grid[i][j]
prev = cur
return prev[-1]
print(min_path_sum_two_rows([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7Space drops from O(mn) to O(n). The code maps directly onto the 2D version: prev[j] is dp[i-1][j] and cur[j-1] is dp[i][j-1]. Start here if you are unsure whether a one-row version is safe.
Step Two: One Row, Overwritten in Place
In the two-row version, cur[j] reads prev[j] once and then never needs it again. So you can write the new value into the same slot. One array does the job if you update it left to right:
- Just before
dp[j]is overwritten, it still holds the value from the row above. dp[j - 1]was overwritten a moment earlier, so it already holds the current row's value to the left.
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 initialization handles the boundaries. Filling dp with infinity stands for the "row -1" that does not exist, so on the first row min(inf, dp[j - 1]) picks the left neighbor. Setting dp[0] = 0 before the loop lets dp[0] += grid[i][0] build the first column one row at a time.
Here is the array after each row of the example grid:
| After row | dp[0] | dp[1] | dp[2] |
|---|---|---|---|
| start | 0 | inf | inf |
| 0 | 1 | 4 | 5 |
| 1 | 2 | 7 | 6 |
| 2 | 6 | 8 | 7 |
Each row of this table matches the corresponding row of the full 2D table. The array always holds the most recent completed row, plus a partial current row while the inner loop runs.
The Same Trick for Counting Paths
Path counting with obstacles shrinks the same way. The update dp[j] += dp[j - 1] reads as "old above plus new left":
def unique_paths_with_obstacles_1d(grid):
n = len(grid[0])
dp = [0] * n
dp[0] = 1
for row in grid:
for j in range(n):
if row[j] == 1:
dp[j] = 0
elif j > 0:
dp[j] += dp[j - 1]
return dp[-1]
print(unique_paths_with_obstacles_1d([[0, 0, 0], [0, 1, 0], [0, 0, 0]])) # 2There are two details to check. First, the loop starts at j = 0 so that a blocked cell in the first column resets dp[0]. After that reset, every cell below it in that column also stays at zero, which is correct. Second, a blocked start cell sets dp[0] to zero on the first row, so the answer comes out as 0 with no special case.
When a Cell Also Reads the Diagonal
Some recurrences read dp[i-1][j-1], the cell above and to the left. Maximal square and edit distance are examples. In a left-to-right single row, that value has already been overwritten by the time you need it, because it was the old dp[j - 1]. The fix is to save it in one extra variable before you overwrite each slot:
def maximal_square_1d(matrix):
n = len(matrix[0])
dp = [0] * (n + 1)
best = 0
for row in matrix:
diag = 0 # holds dp[i-1][j-1]
for j in range(1, n + 1):
saved = dp[j] # dp[i-1][j], becomes the next diagonal
if row[j - 1] == '1':
dp[j] = 1 + min(dp[j], dp[j - 1], diag)
best = max(best, dp[j])
else:
dp[j] = 0
diag = saved
return best * best
print(maximal_square_1d([['1', '0', '1', '0', '0'],
['1', '0', '1', '1', '1'],
['1', '1', '1', '1', '1'],
['1', '0', '0', '1', '0']])) # 4Look at the else: dp[j] = 0 branch. In the 2D version a '0' cell could be skipped, because the table started at zero. In one row, the slot still holds the value from the row above, so skipping it would leave a stale value behind. Every slot must be written on every row. This is the most common bug when turning a 2D solution into a 1D one.
Picking the Shorter Dimension
The row you keep has length n. If the grid is tall and narrow, that is already small. If it is wide and short, such as 10 rows by 100,000 columns, a column-sized array would be much smaller. For symmetric move sets like right/down, transposing the grid gives the same answer, so you can always keep the shorter side:
def min_path_sum_min_space(grid):
if len(grid[0]) > len(grid):
grid = [list(col) for col in zip(*grid)]
return min_path_sum(grid)
print(min_path_sum_min_space([[1, 3, 1, 2, 9]])) # 16Transposing here builds a full copy of the grid, which defeats the purpose when memory is tight. In that case, iterate column by column over the original grid instead of copying it. For edit distance, choose the shorter string as the inner dimension.
| Version | Time | Extra space | Keeps full table? |
|---|---|---|---|
| Full 2D table | O(mn) | O(mn) | yes |
| Two rows | O(mn) | O(n) | no |
| One row, in place | O(mn) | O(n) | no |
| One row along shorter side | O(mn) | O(min(m, n)) | no |
Time never changes. Rolling arrays only reduce memory.
What You Give Up
A rolling array keeps only the frontier. Once a row is overwritten, you cannot tell which neighbor each cell came from. If you need the actual route, not just its cost, you need the full table or some other record of the choices. The next chapter covers that. Debugging also gets harder, because you can no longer print the whole table to check intermediate values. Write and test the 2D version first, then compress it.
Use a rolling array when:
- the recurrence reads only the current row and the row above,
- you need only the final value, or a running best like
bestin maximal square, - memory is the real limit, for example when m × n is in the hundreds of millions.
Exercise
In the one-row minpathsum, a teammate changes the inner loop to for j in range(n - 1, 0, -1):. On the grid [[1, 3, 1], [1, 5, 1], [4, 2, 1]], what goes wrong, and why?
Show answer
Going right to left, dp[j - 1] has not been updated yet when dp[j] reads it, so it still holds the previous row's value (above-left), not the current row's left neighbor. On row 0 every dp[j] for j ≥ 1 becomes min(inf, inf) + grid = inf, because dp[j - 1] is still inf from the start. The function returns inf instead of 7. Dependencies on the new left value need a left-to-right loop.
Exercise
Convert the 2D edit_distance(a, b) to use one row of length len(b) + 1. Which values must you set at the start of each row i, and which value must you save before overwriting dp[j]?
Show answer
Before the inner loop of row i, set diag = dp[0] (the old dp[i-1][0], which equals i - 1), then set dp[0] = i. Inside the loop, save old = dp[j] (that is dp[i-1][j]) before writing. If a[i-1] == b[j-1], set dp[j] = diag. Otherwise set dp[j] = 1 + min(dp[j], dp[j-1], diag). Then set diag = old. The first row is initialized as dp[j] = j.
Exercise
A grid has 50,000 rows and 20 columns, with right/down moves and float costs. Estimate the extra memory for the full 2D table, the one-row version, and say whether transposing helps.
Show answer
The full table holds 1,000,000 entries. As Python floats in a list that is roughly 8 MB of pointers plus the float objects, so tens of MB. The one-row version holds 20 entries, which is negligible. Transposing would make the row 50,000 long, so it hurts here. Keep the row along the 20-column side, which the code already does.