Sub topic 3
Computing the Length in Two Rows
This chapter assumes you already know the bottom-up LCS table from the previous chapter, and that you are comfortable with Big-O notation and Python lists.
Computing the Length in Two Rows
Row i of the table reads only from row i - 1. So you can keep two rows instead of the full table. If you run the rows over the shorter sequence, extra space drops to O(min(m, n)), and time stays O(mn). The cost is that the full table is gone, so you can no longer trace back through it.
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]
def indel_distance(a, b):
return len(a) + len(b) - 2 * lcs_length_two_rows(a, b)
print(lcs_length_two_rows("ABCBDAB", "BDCABA")) # 4
print(indel_distance("ABCBDAB", "BDCABA")) # 5Ties and Multiple Longest Subsequences
Two sequences can have more than one LCS. For example, "AB" and "BA" have two, "A" and "B". During traceback, when dp[i-1][j] == dp[i][j-1], both moves lead to a valid answer. The tie-breaking rule (>= prefers moving up) decides which one you get.
LCS and Insert/Delete Edit Distance
If substitutions are not allowed, the fewest insertions and deletions needed to turn a into b is m + n - 2 * LCS. You keep the characters in the LCS, delete everything else from a, and insert everything else from b. The indel_distance function above computes exactly this.
From LCS to Diff Output
Line-based diff tools treat each line as one symbol. Lines in the LCS are printed as unchanged. Lines only in the old file are shown as - (deleted), and lines only in the new file are shown as + (added).
Contrast: Longest Common Substring
| Problem | On a mismatch | Answer |
|---|---|---|
| Subsequence | `max(up, left)` | `dp[m][n]` |
| Substring | reset to `0` | largest value anywhere in the table |
A substring must be contiguous, so any mismatch breaks the run.
Hirschberg's Algorithm: Reconstruction in Linear Space
Hirschberg's algorithm gives you an actual LCS without storing the full table. It splits a in half. It then runs a two-row pass forward over the first half and another backward over the second half. The split point k in b is where the sum of the two passes is largest. It recurses on both halves. Time is still O(mn), and working space is linear.
Beyond Two Sequences: Multi-Sequence LCS and NP-Hardness
For a fixed number of sequences k, the DP table grows to k dimensions, and the cost is about O(n^k). When the number of sequences is arbitrary, LCS is NP-hard. In practice, people fall back on heuristics or approximations.
Exercise
Using insert/delete-only edit distance, how many operations turn "kitten" into "sitting"?
Show answer
The LCS is "ittn", which has length 4. The distance is 6 + 7 - 2*4 = 5.