Sub topic 10
Computing the Length in Two Rows
This chapter assumes you have read the bottom-up tabulation chapter, can read nested Python loops, and know Big-O notation for space. The full table for strings of lengths m and n holds (m+1)(n+1) integers. If you only need the length of the LCS, you can compute it with far less memory.
Which Cells a Cell Needs
Look at the update rule from the tabulation chapter. Cell dp[i][j] reads at most three other cells:
dp[i-1][j-1], diagonally up and left, used when the characters matchdp[i-1][j], directly abovedp[i][j-1], directly to the left
None of these is more than one row above. Once row i is finished, rows 0 through i-1 are never read again.
The Two-Row Implementation
Keep two lists. prev holds the finished previous row, and curr is the row being filled. When curr is done, it becomes prev. To make each row as short as possible, the code first swaps the inputs so that b is the shorter string.
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 swap is safe because LCS is symmetric: LCS(a, b) has the same length as LCS(b, a).
Costs
| Approach | Time | Extra space | Can trace back? |
|---|---|---|---|
| Full table | O(mn) | O(mn) | Yes |
| Two rows | O(mn) | O(min(m, n)) | No |
Time does not change, because the code still visits every (i, j) pair once. Only the memory shrinks.
Common Errors
- Forgetting the swap. The answer is still correct, but the rows are as long as the longer string, which wastes memory.
- Collapsing to one row without saving the diagonal. A single-list version is possible, but writing
row[j]destroys the old value thatrow[j+1]needs as its diagonal. You must keep that old value in a temporary variable before you overwrite it. - Expecting to recover the subsequence. Traceback walks backward through every row, and those rows are gone. To get the subsequence in linear space, use Hirschberg's algorithm, covered in a later chapter.
Exercise
You compare a 10,000-line file with a 50-line file using lcslengthtwo_rows. About how many integers do the prev and curr lists hold together, and how does that compare with the full table?
Show answer
After the swap, b is the 50-line file, so each row has 51 entries and the two rows hold about 102 integers. The full table would hold 10,001 × 51 = 510,051 integers.
Exercise
Why can't you reconstruct the LCS string from the final prev list alone?
Show answer
Traceback starts at the bottom-right cell and needs earlier rows to decide whether to move up, left, or diagonally. The two-row method has thrown those rows away, so only the last row's lengths are left.