Sub topic 6
Keeping the Diagonal: Single-Row Edit Distance
This chapter assumes you know the edit distance recurrence and its usual full-table solution. It also builds on the two earlier chapters on two-row rolling arrays and on loop direction for in-place updates. Here you will fold a two-dimensional table into one array, even though the recurrence reads a value that the in-place update would normally overwrite.
The recurrence and its three reads
Edit distance counts the minimum number of insertions, deletions, and substitutions needed to turn string s into string t. Let dp[i][j] be the distance between the first i characters of s and the first j characters of t:
dp[0][j] = janddp[i][0] = i, because an empty prefix needs that many insertions or deletions.- 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]). These are substitute, delete, and insert.
Each cell reads from three neighbours:
| Neighbour | Table cell | Row it lives in | Meaning |
|---|---|---|---|
| Up | `dp[i-1][j]` | previous row | delete `s[i-1]` |
| Left | `dp[i][j-1]` | current row | insert `t[j-1]` |
| Diagonal | `dp[i-1][j-1]` | previous row | match or substitute |
Only the previous row and the current row are read, so a two-row version works directly. The question here is whether a single array of length n + 1 can do the same job.
What goes wrong in one array
Suppose a single array dp holds the table, and row i is computed left to right on top of row i-1. Just before column j is written, the array looks like this:
dp[0..j-1]already hold row i values, which were just written.dp[j..n]still hold row i-1 values, which are not yet overwritten.
That gives you two of the three reads for free:
dp[j]is still the old value, which is the up neighbourdp[i-1][j].dp[j-1]is the new value, which is the left neighbourdp[i][j-1].
The diagonal dp[i-1][j-1] used to sit in dp[j-1], but the previous step replaced it with the row i value. It is gone from the array. The 0/1 knapsack trick of reversing the loop does not help here. Going right to left would keep the diagonal intact but destroy the left neighbour, which is just as necessary.
The fix: one variable carries the diagonal
The lost value only has to survive for one step. Before you overwrite dp[j], its old contents are dp[i-1][j], and that is exactly the diagonal that column j + 1 will need. So you copy it into a temporary variable, write the new value, and pass the copy along as diag.
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
return dp[n]
print(edit_distance("sun", "sat")) # 2
print(edit_distance("kitten", "sitting")) # 3
print(edit_distance("", "abc")) # 3
print(edit_distance("abc", "")) # 3Each line has a specific job:
diag = dp[0]runs beforedp[0] = i. The olddp[0]isi - 1, which isdp[i-1][0], the diagonal for column 1.temp = dp[j]savesdp[i-1][j]before the write destroys it.- Inside
min,dp[j]is read before the assignment finishes, so it is still the up value. diag = tempshifts the saved value one column right.
Time stays at O(mn). Space drops from O(mn) to O(n + 1) array slots plus two scalars.
Tracing a row
Take s = "sun" and t = "sat". Row 0 is [0, 1, 2, 3], and after i = 1 (character s) the array is [1, 0, 1, 2]. Here is row i = 2, for character u:
| Step | `diag` used | up `dp[j]` | left `dp[j-1]` | Chars | New `dp[j]` | Array after |
|---|---|---|---|---|---|---|
| start | – | – | – | – | `dp[0] = 2` | `[2, 0, 1, 2]` |
| j = 1 | 1 | 0 | 2 | u vs s | 1 + min(1, 0, 2) = 1 | `[2, 1, 1, 2]` |
| j = 2 | 0 | 1 | 1 | u vs a | 1 + min(0, 1, 1) = 1 | `[2, 1, 1, 2]` |
| j = 3 | 1 | 2 | 1 | u vs t | 1 + min(1, 2, 1) = 2 | `[2, 1, 1, 2]` |
At j = 2, the diagonal value 0 is dp[1][1], the cost of turning s into s. By then the array slot dp[1] already holds 1, so without the saved copy the substitution path through 0 would be lost. Row 3 (character n) produces [3, 2, 2, 2], and the answer is 2: substitute u→a and n→t.
The tempting broken version
The most common mistake is to read dp[j-1] as if it were still the diagonal:
def edit_distance_buggy(s, t):
n = len(t)
dp = list(range(n + 1))
for i in range(1, len(s) + 1):
dp[0] = i
for j in range(1, n + 1):
if s[i - 1] == t[j - 1]:
dp[j] = dp[j - 1] # this is LEFT, not DIAGONAL
else:
dp[j] = 1 + min(dp[j - 1], dp[j], dp[j - 1])
return dp[n]
print(edit_distance_buggy("ab", "ab")) # 2, but the correct answer is 0The bug does not crash, and on many inputs the result is off by only a little, so random tests on short strings can miss it. Two identical strings make a good sanity check, because the correct answer is always 0.
Edge cases and refinements
Empty strings
If s is empty, the outer loop never runs and the function returns dp[n] = n. If t is empty, dp is [0], the inner loop never runs, dp[0] becomes len(s), and that value is returned. Both base cases come out right without special handling.
Making the row the shorter string
With unit costs, edit distance is symmetric, so you can swap the arguments to make t the shorter one. Space then becomes O(min(m, n)):
def edit_distance_min_space(s, t):
if len(t) > len(s):
s, t = t, s
return edit_distance(s, t)
print(edit_distance_min_space("intention", "execution")) # 5Weighted costs
With different costs for insertion, deletion, and substitution, the same single-row structure still works. Swapping the strings, however, turns insertions into deletions. If you swap, you must also swap those two costs.
def weighted_edit_distance(s, t, ins=1, dele=1, sub=1):
if len(t) > len(s):
s, t = t, s
ins, dele = dele, ins
n = len(t)
dp = [j * ins for j in range(n + 1)]
for i in range(1, len(s) + 1):
diag = dp[0]
dp[0] = i * dele
for j in range(1, n + 1):
temp = dp[j]
if s[i - 1] == t[j - 1]:
dp[j] = diag
else:
dp[j] = min(diag + sub, dp[j] + dele, dp[j - 1] + ins)
diag = temp
return dp[n]
print(weighted_edit_distance("ab", "abcd", ins=1, dele=5)) # 2
print(weighted_edit_distance("abcd", "ab", ins=1, dele=5)) # 10The two calls give different results because adding two characters is cheap while removing two is expensive. A version that swapped the strings but not the costs would print 10 and 2.
When the saved diagonal is not enough
The technique works when each cell reads only cells that are adjacent in the previous row. If a recurrence reads dp[i-1][j-2] or anything further left, you need one saved scalar per overwritten column it reaches. At that point a two-row array is usually clearer and costs only one extra row.
What you give up
A single row stores only distances, never which edit was chosen. You can still compute the distance, but you can no longer walk back through the table to list the edits. A later chapter on reconstruction after compression covers how to get the edit script back.
Two rows or one?
| Aspect | Two rows | One row plus `diag` |
|---|---|---|
| Memory | 2(n + 1) slots | (n + 1) slots + 2 scalars |
| Diagonal access | `prev[j-1]`, always valid | must be saved by hand |
| Risk of silent bugs | low | moderate (statement order) |
| Allocation per row | new list or swap | none |
Both versions are O(n). Choose one row when memory is tight or allocation inside hot loops costs you something. Choose two rows when clarity matters more than a factor of two.
Exercise
The LCS recurrence is curr[j] = prev[j-1] + 1 when x[i-1] == y[j-1], otherwise max(prev[j], curr[j-1]). Rewrite it to use a single array dp and a diag variable. Which statements must run before dp[j] is overwritten?
Show answer
Keep dp = [0] * (len(y) + 1). For each i, set diag = 0, which is dp[i-1][0], and leave dp[0] at 0. For each j, set temp = dp[j]. Then, if the characters match, dp[j] = diag + 1; otherwise dp[j] = max(dp[j], dp[j-1]). Finally set diag = temp. The read of dp[j] into temp, and its use as the "up" value inside max, must both happen before dp[j] is assigned. The diagonal then always comes from diag, never from dp[j-1].
Exercise
Someone writes the inner loop of single-row edit distance from j = n down to 1, so that dp[j-1] still holds the previous-row value. Why is this still wrong?
Show answer
Going right to left keeps dp[j-1] as dp[i-1][j-1], so the diagonal is preserved. But the left neighbour dp[i][j-1] has not been computed yet at that point, so the insertion option is lost. The recurrence needs one value from the current row (left) and two from the previous row (up and diagonal). No loop direction keeps all three in the array, which is why one extra scalar is needed.
Exercise
Using editdistance, what does editdistance("abc", "abc") return, and what does editdistancebuggy("abc", "abc") return? Explain the buggy value.
Show answer
The correct function returns 0. The buggy one returns 3. In row i, column 1 matches for i = 1 and copies the left value dp[0] = 1 instead of the diagonal 0. Each later match on the main diagonal copies its left neighbour, which carries that extra 1 forward. Every row adds one more, so the result equals the string length.