Sub topic 10
Computing the Length in Two Rows
This chapter assumes you have already built the bottom-up LCS table from earlier chapters. You should be able to read the recurrence dp[i][j] and know why the full table costs O(mn) time and O(mn) space. You should also be comfortable with Python lists and with the difference between copying a list and aliasing it.
The full table serves two purposes. It gives the LCS length in dp[m][n], and it supports the traceback that recovers an actual subsequence. If you only need the length, most of that table is wasted memory. Two 10,000-character strings need a table of about 100 million cells. In CPython, each cell is an 8-byte pointer in a list, so the table takes roughly 800 MB before you count the integer objects themselves. The two-row version of the same computation fits in a few hundred kilobytes.
Which Cells a Cell Actually Reads
Look again at the recurrence for cell (i, j):
- If
a[i-1] == b[j-1], thendp[i][j] = dp[i-1][j-1] + 1. - Otherwise,
dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
Every cell reads from only three neighbours. Two of them, diagonal-up-left and directly above, sit in row i-1. The third, directly left, sits in row i. No cell ever reads row i-2 or anything earlier. Once row i is complete, row i-1 has nothing left to contribute and can be thrown away.
This dependency pattern is all the optimization needs. You keep a prev row and a curr row, fill curr from left to right, and then promote curr to prev.
The Two-Row Implementation
def lcs_length_two_rows(a, b):
if len(b) > len(a):
a, b = b, a
prev = [0] * (len(b) + 1)
for x in a:
curr = [0] * (len(b) + 1)
for j, y in enumerate(b, 1):
if x == y:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev = curr
return prev[-1]
print(lcs_length_two_rows("ABCBDAB", "BDCABA")) # 4The function makes three deliberate choices:
- The swap at the top. Rows run along
b, so each row haslen(b) + 1cells. Swapping makesbthe shorter input, which brings extra space down to O(min(m, n)). LCS is symmetric (LCS(a, b)has the same length asLCS(b, a)), so the swap never changes the answer. curr[0]stays 0. Column 0 is the base case "empty prefix ofb". A fresh list of zeros already holds that value, and the inner loop starts atj = 1.prev = currhappens after the inner loop. Rebinding the name only after the row is finished means the next iteration reads a completed row.
Time is unchanged at O(mn): the same number of cells is computed, and each takes constant work. The only change is that the code keeps two rows of cells at once instead of all of them.
Avoiding a new list on every row
Allocating curr on every outer iteration costs O(m) allocations. You can allocate two buffers once and swap them:
def lcs_length_swap(a, b):
if len(b) > len(a):
a, b = b, a
n = len(b)
prev = [0] * (n + 1)
curr = [0] * (n + 1)
for x in a:
for j in range(1, n + 1):
if x == b[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")) # 4The swap is safe because the inner loop overwrites every cell curr[1..n] before reading it, and curr[0] is never written, so it stays 0. The old values left in the recycled buffer are never read. After the final swap, the last completed row lives in prev, which is why the function returns prev[n].
The Aliasing Bug
The most common mistake when writing this from memory is to make the two rows the same list:
def lcs_length_buggy(a, b):
if len(b) > len(a):
a, b = b, a
prev = [0] * (len(b) + 1)
curr = prev # BUG: this is the same list, not a second row
for x in a:
for j, y in enumerate(b, 1):
if x == y:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev = curr
return prev[-1]
print(lcs_length_buggy("AXX", "AA")) # 2 (wrong)
print(lcs_length_two_rows("AXX", "AA")) # 1 (correct)Trace the first row, where x = 'A'. At j = 1, the code writes 1 into position 1. At j = 2, it reads prev[1] as the diagonal, but prev and curr are the same list, so it sees the 1 it just wrote. The result is 2, which means the single 'A' in "AXX" has been matched twice. Overwriting the diagonal before reading it always counts one character more than once like this. The error stays hidden on many inputs, including the running example, because it only shows up when a character repeats in the row string. Inputs with repeated symbols belong in your tests for exactly this reason.
Going Down to One Row
Fixing the alias properly gives a one-row version. When you are about to overwrite row[j], it still holds dp[i-1][j], the "above" value. The value you lose is the old row[j-1], which the next cell needs as its diagonal. Save it in a variable before you overwrite it:
def lcs_length_one_row(a, b):
if len(b) > len(a):
a, b = b, a
row = [0] * (len(b) + 1)
for x in a:
diag = 0 # dp[i-1][0]
for j, y in enumerate(b, 1):
above = row[j] # dp[i-1][j], about to be overwritten
if x == y:
row[j] = diag + 1
else:
row[j] = max(above, row[j - 1])
diag = above # becomes dp[i-1][j-1] for the next j
return row[-1]
print(lcs_length_one_row("ABCBDAB", "BDCABA")) # 4
print(lcs_length_one_row("AXX", "AA")) # 1The asymptotic space is still O(min(m, n)). You save one row's worth of memory and pay with a slightly harder invariant to keep straight. Many library implementations use this form.
Checking the Optimizations Against the Full Table
Space optimizations are easy to get subtly wrong, so compare them against the plain table on many random inputs. A small alphabet produces plenty of repeated characters, which is the case that catches the aliasing bug. The script below includes its own reference implementation so it runs as shown.
import random
def lcs_length_full(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[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]
def lcs_length_two_rows(a, b):
if len(b) > len(a):
a, b = b, a
prev = [0] * (len(b) + 1)
for x in a:
curr = [0] * (len(b) + 1)
for j, y in enumerate(b, 1):
curr[j] = prev[j - 1] + 1 if x == y else max(prev[j], curr[j - 1])
prev = curr
return prev[-1]
def lcs_length_one_row(a, b):
if len(b) > len(a):
a, b = b, a
row = [0] * (len(b) + 1)
for x in a:
diag = 0
for j, y in enumerate(b, 1):
above = row[j]
row[j] = diag + 1 if x == y else max(above, row[j - 1])
diag = above
return row[-1]
random.seed(1)
for _ in range(2000):
a = "".join(random.choice("AB") for _ in range(random.randint(0, 12)))
b = "".join(random.choice("AB") for _ in range(random.randint(0, 12)))
expected = lcs_length_full(a, b)
assert lcs_length_two_rows(a, b) == expected, (a, b)
assert lcs_length_one_row(a, b) == expected, (a, b)
print("all checks passed")Empty strings are covered too: the inner loop never runs, so the functions return 0. Nothing in the code depends on the inputs being strings. Lists of lines, tokens, or any other comparable items work the same way, which matters for diff tools in a later chapter.
What You Give Up
| Approach | Time | Extra space | Can trace back an LCS? |
|---|---|---|---|
| Full table | O(mn) | O(mn) | Yes |
| Two rows | O(mn) | O(min(m, n)) | No |
| One row plus `diag` | O(mn) | O(min(m, n)) | No |
The traceback walks from dp[m][n] back toward dp[0][0] and reads cells from every row. Those rows are gone. You know how long the LCS is, but you cannot say which characters make it up.
That strategy is Hirschberg's algorithm, covered later in this tutorial. It runs the two-row pass forward over one half of the input and backward over the other half. The two final rows tell it where an optimal path crosses the middle, and it recurses on each side. Treat the function in this chapter as a building block: Hirschberg's algorithm uses it to compute a last row, without needing the full table.
The choice comes down to this. Use the full table when the inputs are small enough and you need the subsequence. Use two rows or one row when you need only the length, or a derived number such as the insert/delete distance. Use Hirschberg's algorithm when you need the subsequence and the full table will not fit in memory.
Exercise
Suppose you remove the swap at the top of lcslengthtwo_rows and call it with a of length 1,000,000 and b of length 50. Is the answer still correct, and what happens to the extra space?
Show answer
The answer is still correct because LCS length is symmetric and the swap only chooses which string runs along the rows. Space is unaffected in this call: rows are sized by len(b) + 1 = 51, which is already the shorter string. The swap matters only for the reverse call (a of length 50, b of length 1,000,000). Without it, each row would hold 1,000,001 cells instead of 51.
Exercise
In lcslengthone_row, what goes wrong if you move the line "diag = above" so that it runs before the if/else statement instead of after it?
Show answer
The match branch would compute row[j] = above + 1, using dp[i-1][j] instead of dp[i-1][j-1]. That lets the current character of a match again against a character it was already counted with, so the function can overcount. For example, ("AXX", "AA") would return 2 instead of 1. The diagonal must still hold the previous column's old value when the match branch reads it.
Exercise
Write a function lcslengthlast_row(a, b) that returns the entire final row (a list of length len(b) + 1) instead of only its last value, without swapping the inputs. Why must it not swap?
Show answer
Use the two-row loop unchanged but drop the swap and return prev instead of prev[-1]. Entry j of the result is the LCS length of all of a against b[:j]. If you swapped, the row would index prefixes of the other string, and a caller such as Hirschberg's algorithm, which needs lengths against prefixes of a specific string, would get answers about the wrong string.