Sub topic 6
Keeping the Diagonal: Single-Row Edit Distance
This chapter assumes you know the two-row rolling array from earlier chapters. It also assumes you know why loop direction matters when you update a single array in place. Here we take edit distance down to one row. That needs a single extra variable, because one of its three dependencies would otherwise be lost.
The recurrence and its three reads
Edit distance counts the fewest insertions, deletions, and substitutions that turn string s into string t. The full table defines dp[i][j] as the distance between the first i characters of s and the first j characters of t:
- If
s[i-1] == t[j-1], thendp[i][j] = dp[i-1][j-1]. - Otherwise,
dp[i][j] = 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]).
Each cell reads three neighbors: the one above, the one to its left, and the one diagonally up-left.
Why one row almost works
Suppose a single array dp holds row i-1 and you sweep j left to right, overwriting it with row i. When you reach column j:
| Needed value | Where it is in the single row | Still available? |
|---|---|---|
| `dp[i-1][j]` (above) | `dp[j]`, not yet overwritten | Yes |
| `dp[i][j-1]` (left) | `dp[j-1]`, just overwritten | Yes, and the new value is the one you want |
| `dp[i-1][j-1]` (diagonal) | was in `dp[j-1]` | No, the previous step overwrote it |
Two of the three reads are free. The diagonal is gone. Changing the loop direction does not help: a right-to-left sweep keeps the diagonal but loses the left neighbor, which the recurrence also needs.
Saving the diagonal
The fix is to copy dp[j] into a temporary variable before you overwrite it. After you write the new dp[j], that saved old value becomes the diagonal for column j+1.
def edit_distance(s, t):
n = len(t)
dp = list(range(n + 1))
for i in range(1, len(s) + 1):
diag = dp[0]
dp[0] = i
for j in range(1, n + 1):
temp = dp[j]
if s[i - 1] == t[j - 1]:
dp[j] = diag
else:
dp[j] = 1 + min(diag, dp[j], dp[j - 1])
diag = temp
# dp now holds row i
return dp[n]
print(edit_distance("kitten", "sitting")) # 3
print(edit_distance("", "abc")) # 3
print(edit_distance("flaw", "lawn")) # 2Here is what each line does:
dp = list(range(n + 1))is row 0. Turning an empty prefix intojcharacters takesjinsertions.diag = dp[0]savesdp[i-1][0]beforedp[0] = ioverwrites it. That saved value is the diagonal forj = 1.temp = dp[j]saves the old "above" value. The linediag = temphands it on as the next column's diagonal.
Space falls from O(mn) to O(n). If you swap the strings so t is the shorter one, it becomes O(min(m, n)). Time stays O(mn).
Common errors
- Updating
diagbefore you writedp[j]. The current cell then reads its own "above" value as the diagonal. - Forgetting to reset
diagat the start of each row. The last column's value from the previous row leaks into column 1. - Expecting to recover the edit script from this array. Only the last row survives. Later chapters cover reconstruction.
Exercise
In the single-row loop, suppose you delete the line temp = dp[j] and write diag = dp[j] after the if/else. What does diag hold when the next column runs, and why is that wrong?
Show answer
It holds the new value dp[i][j], which is the left neighbor of the next cell, not its diagonal. The next cell needs dp[i-1][j], the old value from before the overwrite, so the result can come out too low.
Exercise
Trace edit_distance("ab", "b"). Give the array after row 1 and after row 2.
Show answer
Row 0 is [0, 1]. Row 1 (s[0] = 'a', no match): dp[0] = 1, dp[1] = 1 + min(0, 1, 1) = 1, so the array is [1, 1]. Row 2 (s[1] = 'b', match): dp[0] = 2, dp[1] = diag = 1, so the array is [2, 1]. The answer is 1.