Sub topic 13
Edit Distance: When Two Strings Form a Grid
So far, every grid in this tutorial has been a real board of cells. This chapter covers a problem that has no board at all. You get two strings, and the grid comes from their prefixes. Edit distance is the standard example. Once you see why it is a grid problem, you will spot the same structure in longest common subsequence, sequence alignment, and many string-matching problems.
This chapter assumes you already know the grid DP workflow from earlier chapters: define the state, derive the recurrence from the allowed moves, set base cases on the edges, and fill the table in dependency order. It also assumes you can read a padded table, meaning one with an extra row and column at index 0.
The Problem
The edit distance (also called Levenshtein distance) between strings a and b is the minimum number of single-character operations needed to turn a into b. Three operations are allowed:
- Insert one character.
- Delete one character.
- Substitute one character for another.
For example, turning horse into ros takes 3 operations:
horse→rorse(substitutehwithr)rorse→rose(delete the secondr)rose→ros(deletee)
No sequence of 2 operations works, so the distance is 3.
Defining the State
The key decision is what a cell means. Let m = len(a) and n = len(b). Define:
dp[i][j] = the edit distance between the first i characters of a and the first j characters of b.
Rows index prefixes of a and columns index prefixes of b. The table has (m + 1) × (n + 1) cells because the empty prefix counts. Row 0 stands for the empty prefix of a, and column 0 stands for the empty prefix of b. The answer is in dp[m][n], the bottom-right corner, just like the goal cell in a path problem.
From Operations to Moves
Look at the last characters of the two prefixes, a[i - 1] and b[j - 1]. Any optimal edit script must deal with them in one of four ways, and each way points to a neighboring cell:
| Case | What happens | Cost | Neighbor used |
|---|---|---|---|
| Match | `a[i-1] == b[j-1]`, so keep both | 0 | `dp[i-1][j-1]` (diagonal) |
| Substitute | Replace `a[i-1]` with `b[j-1]` | 1 | `dp[i-1][j-1]` (diagonal) |
| Delete | Remove `a[i-1]` | 1 | `dp[i-1][j]` (up) |
| Insert | Append `b[j-1]` to `a`'s prefix | 1 | `dp[i][j-1]` (left) |
This gives the recurrence:
- If
a[i-1] == b[j-1]:dp[i][j] = dp[i-1][j-1] - Otherwise:
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
Compared with minimum-cost paths, the walker now has three moves (right, down, and diagonal), and each move has its own cost.
Why the Match Case Skips the Minimum
When the characters match, you might expect min(dp[i-1][j-1], 1 + dp[i-1][j], 1 + dp[i][j-1]). That version is also correct, but the extra terms never win. Neighboring cells differ by at most 1, so dp[i-1][j-1] <= dp[i-1][j] + 1 and dp[i-1][j-1] <= dp[i][j-1] + 1. Taking the diagonal directly is safe. The shortcut is only valid when all three operations cost 1. With custom weights, keep the full minimum.
Base Cases
The padded row and column contain real answers, not placeholders:
dp[i][0] = i: turningicharacters into the empty string takesideletions.dp[0][j] = j: buildingjcharacters from the empty string takesjinsertions.
This differs from path counting, where padding usually holds 0 or infinity to mark "no path". Here the edges carry costs, and setting them to 0 is a common bug. With zeroed edges, edit_distance('abc', '') would return 0.
Fill Order
Every cell depends on the cells above, to the left, and diagonally up-left. Filling row by row, left to right, computes all three before they are needed. Column by column also works. The order that fails is anything that visits (i, j) before (i-1, j-1).
The Full Implementation
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')) # 3Here is the filled table for horse and ros. Rows are prefixes of horse and columns are prefixes of ros. The empty prefix is written ∅.
| Row | ∅ | r | o | s |
|---|---|---|---|---|
| ∅ | 0 | 1 | 2 | 3 |
| h | 1 | 1 | 2 | 3 |
| o | 2 | 2 | 1 | 2 |
| r | 3 | 2 | 2 | 2 |
| s | 4 | 3 | 3 | 2 |
| e | 5 | 4 | 4 | 3 |
Check a match cell. At row o, column o, the characters match, so the cell copies its diagonal neighbor dp[1][1] = 1. At row s, column s, the cell copies dp[3][2] = 2. The last cell, row e and column s, is a mismatch: 1 + min(2, 4, 3) = 3.
Complexity
The table has (m + 1)(n + 1) cells and each takes constant work, so time is O(mn) and space is O(mn). For two 10,000-character strings, that is about 100 million cells. Time is acceptable in a compiled language and slow in pure Python. Memory is the bigger problem: a list of lists of Python ints at that size uses several gigabytes.
One Row, Plus One Saved Value
The rolling-array technique from earlier still applies, with one twist. In minimum path sum, a single row was enough because each cell read only "above" (the old dp[j]) and "left" (the new dp[j-1]). Edit distance also reads the diagonal, dp[i-1][j-1]. By the time you reach column j, the one-row array has already overwritten that value with dp[i][j-1]. You have to save it in a variable before it is lost.
def edit_distance_one_row(a, b):
n = len(b)
dp = list(range(n + 1)) # row 0: dp[0][j] = j
for i in range(1, len(a) + 1):
diag = dp[0] # dp[i-1][0]
dp[0] = i # dp[i][0]
for j in range(1, n + 1):
above = dp[j] # dp[i-1][j], before overwrite
if a[i - 1] == b[j - 1]:
dp[j] = diag
else:
dp[j] = 1 + min(above, dp[j - 1], diag)
diag = above # becomes dp[i-1][j-1] for column j+1
return dp[n]
print(edit_distance_one_row('horse', 'ros')) # 3
print(edit_distance_one_row('', 'abc')) # 3Space drops to O(n). Pass the shorter string as b to get O(min(m, n)). Edit distance is symmetric when every operation costs 1, so swapping the arguments is safe.
Common Errors
- Using
a[i]instead ofa[i - 1]. This skips the first character and raises anIndexErroron the last row. - Zero-filled edges. The padding row and column must hold
jandi. - Adding 1 on a match. That turns the algorithm into "count aligned positions", and
edit_distance('a', 'a')returns 1. - Mixing up insert and delete. The total is still correct because both cost 1. Once the costs differ, or when you print the script, the direction matters: moving up consumes a character of
a(delete), and moving left consumes a character ofb(insert). - Forgetting the diagonal in the one-row version. If you use
dp[j - 1]as the diagonal, you read the current row's value, and the result is wrong.
The Same Grid, Other Problems
Changing the moves and their costs turns this table into other well-known algorithms:
| Problem | Match | Mismatch | Edges |
|---|---|---|---|
| Edit distance | `dp[i-1][j-1]` | `1 + min(up, left, diag)` | `i`, `j` |
| Longest common subsequence | `1 + dp[i-1][j-1]` | `max(up, left)` | 0 |
| Weighted alignment | `diag + score(x, y)` | `max(diag + score, up + gap, left + gap)` | multiples of gap |
Damerau–Levenshtein distance also allows swapping two adjacent characters. It adds a fourth transition from dp[i-2][j-2], and that transition only applies when a[i-1] == b[j-2] and a[i-2] == b[j-1].
Exercise
Fill in the edit distance between "kitten" and "sitting" by hand or with the code above. What is it, and which operations achieve it?
Show answer
The distance is 3. Substitute k with s ("sitten"), substitute e with i ("sittin"), and insert g at the end ("sitting").
Exercise
In editdistanceone_row, why can't you replace the variable diag with dp[j - 1] read just before computing dp[j]?
Show answer
When column j is processed, dp[j - 1] has already been overwritten with the current row's value dp[i][j - 1], which is the "left" neighbor. The diagonal value dp[i - 1][j - 1] existed only before that overwrite, so it must be saved in a variable (diag) first.
Exercise
Suppose deleting costs 2, inserting costs 1, and substituting costs 1. Write the recurrence and base cases for dp[i][j].
Show answer
Base cases: dp[i][0] = 2 * i and dp[0][j] = j. For i, j >= 1: dp[i][j] = min(dp[i-1][j] + 2, dp[i][j-1] + 1, dp[i-1][j-1] + (0 if a[i-1] == b[j-1] else 1)). Keep the full minimum even on a match, because the shortcut argument assumed equal unit costs.