Sub topic 4
From a Full Table to Two Rows
This chapter assumes you can write a bottom-up DP table for a two-dimensional problem such as longest common subsequence (LCS), and that you can read a recurrence and say which cells it reads, as covered in the dependency-analysis chapter. You also need Big-O space analysis and Python lists.
The previous chapter shrank one-dimensional recurrences to a few variables. Many classic problems use a 2D table indexed by two positions, for example a position in each of two strings. Building the whole (m+1) × (n+1) table is usually wasteful, because each row only reads the row directly above it.
Why the Full Table Is Wasteful
LCS of strings x (length m) and y (length n) uses this recurrence:
dp[i][j] = dp[i-1][j-1] + 1ifx[i-1] == y[j-1]dp[i][j] = max(dp[i-1][j], dp[i][j-1])otherwisedp[0][j] = dp[i][0] = 0
Cell (i, j) reads three neighbours: the diagonal (i-1, j-1), the cell above (i-1, j), and the cell to the left (i, j-1). Two of them are in row i-1 and one is in row i. Row i never reads row i-2 or any earlier row. When the program starts filling row i+1, rows 0 through i-1 are dead data.
Here is the full-table version for reference. Its space is O(m·n).
def lcs_length_full(x, y):
m, n = len(x), len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]The Two-Row Rolling Array
The two-row technique, also called a rolling array, keeps exactly the rows the recurrence reads. prev holds row i-1 and curr holds row i. After a row is finished, it becomes prev for the next iteration.
def lcs_length(x, y):
if len(x) < len(y):
x, y = y, x
prev = [0] * (len(y) + 1)
for i in range(1, len(x) + 1):
curr = [0] * (len(y) + 1)
for j in range(1, len(y) + 1):
if x[i - 1] == y[j - 1]:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev = curr
return prev[len(y)]The mapping from the full table is mechanical:
| Full table | Two rows |
|---|---|
| `dp[i-1][j-1]` | `prev[j-1]` |
| `dp[i-1][j]` | `prev[j]` |
| `dp[i][j-1]` | `curr[j-1]` |
| `dp[i][j]` | `curr[j]` |
| `dp[m][n]` | `prev[n]` after the loop |
The answer is read from prev, not curr, because the last statement in the loop body moves the final row into prev. If x is empty the loop never runs and prev[n] is the base row, which is 0 and correct.
Choosing which dimension to keep
The row length sets the space cost, so the code makes the shorter string the column dimension. Space becomes O(min(m, n)) and time stays O(m·n). The swap is valid only because LCS is symmetric: LCS(x, y) == LCS(y, x). For a recurrence that treats its two inputs differently, such as edit distance with different insert and delete costs, swapping the inputs changes the answer. In that case you have to keep the orientation, or swap the costs along with the strings.
Avoiding Per-Row Allocation
The version above allocates a fresh curr for each row. That is simple and correct, but it creates m short-lived lists. A tighter version allocates two buffers once and swaps their references:
def lcs_length_swap(x, y):
if len(x) < len(y):
x, y = y, x
n = len(y)
prev = [0] * (n + 1)
curr = [0] * (n + 1)
for i in range(1, len(x) + 1):
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev, curr = curr, prev
return prev[n]Reusing a buffer is safe here for two reasons:
- Every cell
curr[1..n]is overwritten before it is read in the new row, so stale values from two rows back are never seen. curr[0]is never written, so it stays at the base value 0 in both buffers.
Neither condition holds automatically in other problems. If the base column changes per row (in edit distance, dp[i][0] = i), you must set curr[0] at the start of each row. If some cells are skipped, for example blocked cells in a grid or a banded DP that only fills j near i, the skipped cells keep values from row i-2. Reset them explicitly.
Common Errors
Aliasing the two rows
Writing prev = curr in the swap version, instead of prev, curr = curr, prev, makes both names point to the same list. The next row then overwrites prev[j-1] before it is read as the diagonal, and the results are wrong. Making the in-place single-array version correct takes deliberate tricks, which the next two chapters cover. Accidental aliasing gets you none of them.
Reading the wrong row at the end
Returning curr[n] after the swap returns row m-1 (or garbage) instead of row m. Trace where the last completed row ends up after the final loop iteration.
Forgetting row-dependent base values
The LCS base column is all zeros, which hides this bug. In problems like edit distance, a reused buffer that never resets curr[0] keeps the base value from two rows earlier.
Verifying the Reduction
Whenever you compress a table, test the compressed version against the full one on random inputs. Both run in the same time, so the check is cheap:
import random
def random_string(k):
return "".join(random.choice("abc") for _ in range(k))
for _ in range(2000):
a = random_string(random.randint(0, 12))
b = random_string(random.randint(0, 12))
expected = lcs_length_full(a, b)
assert lcs_length(a, b) == expected, (a, b)
assert lcs_length_swap(a, b) == expected, (a, b)
print("all checks passed")A small alphabet like "abc" produces many matches and many ties, which exercises both branches of the recurrence. Lengths starting at 0 cover the empty-input edge case.
What the Savings Look Like
For two strings of length 10,000, the full table has about 10⁸ cells. A Python list stores an 8-byte pointer per cell, so the table needs roughly 800 MB before counting the int objects. Two rows of 10,001 cells need about 160 KB. The time does not change: both versions do the same 10⁸ cell updates.
| Version | Space | Time | Can rebuild the subsequence? |
|---|---|---|---|
| Full table | O(m·n) | O(m·n) | Yes, by backtracking |
| Two rows | O(min(m, n)) | O(m·n) | No, only the length |
When Two Rows Apply
The test comes from dependency analysis. If every transition into row i reads only rows i and i-1, two rows are enough. Problems that fit include LCS, grid path counting, minimum path sum, and edit distance. If a transition reaches back k rows, you need k+1 rows, which the modulo-indexing chapter handles. If a transition reads an arbitrary earlier row, as in interval DP where dp[i][j] reads dp[i][k] and dp[k][j], no fixed number of rows works.
Exercise
In lcslengthswap, a teammate replaces prev, curr = curr, prev with prev = curr. Trace x = "ab", y = "ab" and explain what goes wrong.
Show answer
After row 1, prev and curr are the same list, [0, 1, 1]. In row 2 at j = 1, x[1] = 'b' and y[0] = 'a' differ, so curr[1] = max(prev[1], curr[0]) = 1. That write also changes prev[1]. At j = 2 the characters match, so curr[2] = prev[1] + 1 = 2. The result happens to be correct here, but only because the overwritten value was equal to the true diagonal. With x = "aa", y = "aa": row 1 is [0, 1, 1]. In row 2, j = 1 gives curr[1] = prev[0] + 1 = 1, and j = 2 reads prev[1], which now holds the current row's value 1 instead of the diagonal dp[1][1] = 1. That also works by luck. With x = "ba", y = "ab": row 1 is [0, 0, 1], and in row 2 j = 1 sets curr[1] = 1. Then j = 2 reads curr[1] = 1 as the left neighbour and prev[2] = 1, giving 1, which is correct again. The bug is that the diagonal and "above" reads can see values from the current row, so correctness depends on the input. Random testing against lcslengthfull finds a failing case quickly, for example x = "aab", y = "ab" variants with repeated characters. The fix is to keep two distinct buffers and swap references.
Exercise
Write a two-row function unique_paths(grid) that counts paths from the top-left to the bottom-right of a grid of 0s (open) and 1s (blocked), moving only right or down. State its space complexity.
Show answer
def unique_paths(grid): cols = len(grid[0]) prev = [0] cols for r in range(len(grid)): curr = [0] cols for c in range(cols): if grid[r][c] == 1: curr[c] = 0 elif r == 0 and c == 0: curr[c] = 1 else: curr[c] = prev[c] + (curr[c - 1] if c > 0 else 0) prev = curr return prev[cols - 1] Space is O(cols). Allocating a fresh curr per row means blocked cells are always 0, so no stale values from earlier rows leak in. You could transpose the grid first to get O(min(rows, cols)), because path counting is symmetric under transposition.
Exercise
You need the LCS length of a 50,000-character string and a 200-character string. Roughly how many list cells do the full table and the two-row version need, and how much does the orientation choice matter?
Show answer
The full table needs 50,001 × 201, about 10 million cells. With the shorter string as columns, two rows need 2 × 201 = 402 cells. With the longer string as columns they would need 2 × 50,001, about 100,000 cells. Both orientations do about 10 million updates, but keeping the shorter string as the column dimension cuts memory by about 250 times.