Sub topic 13
Edit Distance: When Two Strings Form a Grid
This chapter assumes you already know how to define a grid state, write a recurrence over neighbors, and fill a table row by row, as in the earlier path chapters. You should also be comfortable with Python string indexing.
Some problems never mention a grid, but they still turn into one. Edit distance is the standard example. Given strings a and b, it asks for the fewest single-character insertions, deletions, and substitutions that turn a into b.
Prefixes as Rows and Columns
Let row i stand for the first i characters of a, and column j for the first j characters of b. The state is:
dp[i][j]is the minimum number of edits that turna[:i]intob[:j].
The table has (m + 1) × (n + 1) cells, not m × n. Row 0 and column 0 represent the empty prefix, and they act as the padding row and column from the boundary chapter. Here, though, they hold real answers instead of placeholders.
Edits Are Moves
Each operation consumes characters from one or both strings, so each one is a move into cell (i, j) from a neighbor:
| Move into `(i, j)` from | Operation | Cost |
|---|---|---|
| `(i - 1, j)`, above | Delete `a[i - 1]` | 1 |
| `(i, j - 1)`, left | Insert `b[j - 1]` | 1 |
| `(i - 1, j - 1)`, diagonal | Substitute `a[i - 1]` with `b[j - 1]` | 1 |
| `(i - 1, j - 1)`, diagonal | Characters already match | 0 |
The recurrence takes the cheapest of these moves. When the characters match, the free diagonal move is always at least as good as the others, so the code uses it directly.
Base Cases
Turning a[:i] into the empty string takes i deletions, so dp[i][0] = i. Building b[:j] from nothing takes j insertions, so dp[0][j] = j. Every cell depends only on cells above, to the left, or diagonally up-left, so a plain row-major fill computes each dependency before it is used.
def edit_distance(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
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]
else:
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
return dp[m][n]
print(edit_distance('horse', 'ros')) # 3For 'horse' to 'ros', one optimal script is: substitute h with r, delete r, then delete e.
Common Errors
- Off-by-one indexing. Cell
(i, j)comparesa[i - 1]withb[j - 1]. If you writea[i], you skip the first character and read past the end on the last row. - Zeroed borders. If you leave row 0 and column 0 at zero, the code claims that deleting a whole prefix costs nothing.
- Losing the diagonal in a rolling array. If you shrink the table to one row, overwriting
dp[j - 1]destroys the old diagonal value thatdp[j]still needs. Save it in a temporary variable before you overwrite it.
The solution runs in O(mn) time and uses O(mn) space, or O(min(m, n)) space with a rolling row.
Exercise
Compute edit_distance('kitten', 'sitting') and give one sequence of edits that achieves it.
Show answer
The distance is 3. Substitute k with s (sitten), substitute e with i (sittin), then insert g at the end (sitting).
Exercise
In a one-row version of edit distance, why do you need an extra variable that you don't need for minimum path sum?
Show answer
Minimum path sum reads only the cell above (old dp[j]) and the cell to the left (new dp[j - 1]). Edit distance also reads the diagonal, which is the old value of dp[j - 1], and the row update overwrites that value one step earlier. So you have to save it in a variable such as prev before updating dp[j - 1].