Sub topic 12
Edit distance
Edit distance measures how different two strings are by counting the fewest single-character changes that turn one into the other. This chapter assumes you know the recurrence and table-filling pattern from the longest common subsequence chapter, and that you can read Big-O notation and simple Python.
The problem
The Levenshtein edit distance between strings a (length m) and b (length n) is the minimum number of these operations needed to turn a into b:
- Insert one character.
- Delete one character.
- Substitute one character for another.
Each operation costs 1. For example, SUN becomes SAT in 2 steps: substitute U with A, then substitute N with T. Spell checkers, diff tools and DNA alignment all use this idea.
Subproblems and the recurrence
Let dp[i][j] be the edit distance between the first i characters of a and the first j characters of b. Look at the last characters, a[i-1] and b[j-1]. Every optimal edit sequence ends in one of four ways:
- Match: the characters are equal, so no cost is paid and the answer is
dp[i-1][j-1]. - Substitute: replace
a[i-1]withb[j-1]for1 + dp[i-1][j-1]. - Delete: drop
a[i-1]for1 + dp[i-1][j]. - Insert: append
b[j-1]to the end ofafor1 + dp[i][j-1].
This gives the recurrence:
dp[i][j] = dp[i-1][j-1]ifa[i-1] == b[j-1].- Otherwise
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]).
The base cases are dp[i][0] = i (delete all i characters) and dp[0][j] = j (insert all j characters).
When the characters match, you do not need to compare the match with the other three options. Matching is never worse than any other move on equal characters, so the recurrence takes it directly.
Code
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('SUN', 'SAT')) # 2
print(edit_distance('kitten', 'sitting')) # 3The table is filled row by row, left to right. Every cell needs only its left, upper and upper-left neighbours, so this order always has them ready. Time is O(mn) and space is O(mn).
Tracing by hand
This is the table for SUN (rows) and SAT (columns). It is the format GATE questions expect you to fill in.
| Row | "" | S | A | T |
|---|---|---|---|---|
| "" | 0 | 1 | 2 | 3 |
| S | 1 | 0 | 1 | 2 |
| U | 2 | 1 | 1 | 2 |
| N | 3 | 2 | 2 | 2 |
Take the cell for U and A. The characters differ, so the cell is 1 plus the minimum of 1 (upper), 1 (left) and 0 (upper-left). That is 1. The bottom-right cell holds the answer, 2.
To recover the actual operations, start at dp[m][n] and walk back. At each cell, move to a neighbour that explains its value: diagonal for a match or substitution, up for a delete, left for an insert. Stop at dp[0][0].
Reducing space
Row i depends only on row i-1 and on cells already computed in row i. Two rows are enough, which reduces space to O(min(m, n)) when the shorter string indexes the columns.
def edit_distance_rows(a, b):
if len(b) > len(a):
a, b = b, a
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i] + [0] * len(b)
for j, cb in enumerate(b, 1):
if ca == cb:
cur[j] = prev[j - 1]
else:
cur[j] = 1 + min(prev[j], cur[j - 1], prev[j - 1])
prev = cur
return prev[-1]
print(edit_distance_rows('kitten', 'sitting')) # 3Swapping the strings is safe because the distance is symmetric when all costs are 1. The price of the compact version is that you can no longer backtrack to list the operations.
Relation to LCS
If you allow only insertions and deletions, with no substitution, the distance is m + n - 2 * LCS(a, b). For ABCBDAB and BDCABA the LCS length is 4, so the distance is 7 + 6 - 8 = 5. A substitution counts as one step in edit distance, but it would cost two steps (delete then insert) in this restricted version.
Common errors
- Wrong base cases. Setting row 0 and column 0 to zero is the LCS initialization. For edit distance they must be
jandi. - Adding 1 on a match. A matching pair costs nothing.
- Dropping a neighbour from the minimum. All three of up, left and upper-left are needed when the characters differ.
- Off-by-one indexing.
dp[i][j]coversicharacters, so the characters being compared area[i-1]andb[j-1]. - Assuming a greedy rule works. Aligning first mismatches and fixing them one by one can give a larger count than the optimum. The subproblems overlap, so you need the table.
Exercise
What is the edit distance between SATURDAY and SUNDAY, and how many cells does the table have?
Show answer
The distance is 3: delete A, delete T, and substitute R with N. The table has (8 + 1) x (6 + 1) = 63 cells.
Exercise
For two strings of length 1000, how many table cells does the full version compute, and how much memory does the two-row version need?
Show answer
The full version computes about 1000 x 1000 = 10^6 cells (1001 x 1001 including the base row and column). The two-row version stores two rows of 1001 entries, which is O(n) memory, while the time is still O(mn).