Sub topic 4
From a Full Table to Two Rows
This chapter assumes you can write a bottom-up DP table and read Big-O space bounds. It also assumes you know the longest common subsequence (LCS) recurrence. Earlier chapters showed how to find which states a transition reads. Here we use that analysis on a two-dimensional table.
The full-table cost
The LCS of strings x (length m) and y (length n) fills a table dp[i][j], the LCS length of the prefixes x[:i] and y[:j]:
- If
x[i-1] == y[j-1], thendp[i][j] = dp[i-1][j-1] + 1. - Otherwise,
dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
The full table holds (m+1)(n+1) cells. For two strings of 100,000 characters each, that is about 10^10 integers, which is far too many for most machines.
What a row actually reads
Each cell reads three neighbors: up (dp[i-1][j]), up-left (dp[i-1][j-1]), and left (dp[i][j-1]). Every one of them is in row i-1 or row i. Row i-2 and everything above it are never read again once row i starts.
That means two arrays are enough. One is prev, the finished row i-1. The other is curr, the row being filled.
The two-row LCS
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)]
print(lcs_length("ABCBDAB", "BDCABA")) # 4Two details matter here:
- Swap so rows are short. Rows are indexed by
y, so makingythe shorter string gives O(min(m, n)) space. Time stays O(mn). - The answer is in
prev. After the last iteration,prev = curr, soprev[len(y)]holdsdp[m][n].
Reusing two buffers
Allocating a new curr on every row is simple, but it creates garbage on every iteration. You can allocate both rows once and swap them instead:
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):
curr[0] = 0
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]
print(lcs_length_swap("ABCBDAB", "BDCABA")) # 4Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| Returning `curr[n]` after a swap | Answer comes from an old row | Return `prev[n]` |
| Rows sized to the longer string | Memory is O(max(m, n)) | Swap the inputs first |
| Base column not reset | Values drift between rows | Reset `curr[0]` every row |
| Expecting to rebuild the subsequence | Earlier rows are gone | See the reconstruction chapter |
Two rows give you the optimal value. They do not let you trace back the subsequence itself, because the trace-back needs rows you have discarded. A later chapter covers how to get the solution back.
Exercise
Strings x and y have lengths 200,000 and 500. Roughly how many integers does the full LCS table hold, and how many does the two-row version hold?
Show answer
The full table holds about 200,001 × 501 ≈ 10^8 integers. The two-row version swaps so rows have length 501, so it holds 2 × 501 = 1,002 integers. Time is O(10^8) either way.
Exercise
A recurrence computes dp[i][j] from dp[i-1][j], dp[i-2][j], and dp[i][j-1]. Is two rows enough? If not, how many rows do you need?
Show answer
No. Row i reads row i-2, so you must keep three rows: i-2, i-1, and i. In general, you keep one row for each distinct row offset the transition reads, plus the current row.