Edit distance between two words: what does each table cell mean?
Question
A shop's search box should suggest close matches for typos. Write edit_distance(a, b): the fewest single-letter edits that turn word a into word b. An edit inserts, deletes or replaces one letter. Then explain what each cell of your table means.
edit_distance("cake", "back") # 3 edit_distance("cart", "chart") # 1, insert h edit_distance("", "shoe") # 4
def edit_distance(a, b): ...
Show hints (3)
- "SMALLER PIECES"
Let cell
[i][j]be the fewest edits that turn the firstiletters ofainto the firstjletters ofb. What goes in row 0 and column 0? - "THE LAST LETTERS"
Look at the last letter of each prefix. If they match, they need no edit. If not, the last edit was a delete, an insert or a replace.
- "THE FORMULA"
If
a[i - 1] == b[j - 1], copy the cell up and to the left. Otherwise take 1 plus the smallest of up (delete), left (insert) and up-left (replace). The answer is the bottom-right cell.
Show checked explanation
Fill a table where cell [i][j] is the fewest edits that turn the first i letters of a into the first j letters of b. Row 0 and column 0 count pure inserts and deletes. If the last letters match, copy the up-left cell. Otherwise take 1 plus the smallest of the up, left and up-left cells. The answer is the bottom-right cell.
def edit_distance(a, b): # dist[i][j]: fewest edits that turn a[:i] into b[:j] dist = [[0] * (len(b) + 1) for _ in range(len(a) + 1)] dist[0] = list(range(len(b) + 1)) for i in range(len(a) + 1): dist[i][0] = i for i in range(1, len(a) + 1): for j in range(1, len(b) + 1): if a[i - 1] == b[j - 1]: dist[i][j] = dist[i - 1][j - 1] else: dist[i][j] = 1 + min(dist[i - 1][j], # delete dist[i][j - 1], # insert dist[i - 1][j - 1]) # replace return dist[len(a)][len(b)] print(edit_distance("cake", "back")) print(edit_distance("cart", "chart")) print(edit_distance("", "shoe"))
3 1 4
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Row 0 and column 0 stand for an empty prefix. Turning "" into "bac" takes 3 inserts. Turning "cak" into "" takes 3 deletes.
Here is the table for cake → back. Rows are prefixes of cake, and columns are prefixes of back:
"" | b | a | c | k | |
|---|---|---|---|---|---|
"" | 0 | 1 | 2 | 3 | 4 |
| c | 1 | 1 | 2 | 2 | 3 |
| a | 2 | 2 | 1 | 2 | 3 |
| k | 3 | 3 | 2 | 2 | 2 |
| e | 4 | 4 | 3 | 3 | 3 |
To fill a cell, look at the last letter of each prefix. If they match, they need no edit, so copy the cell up and to the left. Row a, column a is 1, because ca → ba costs the same as c → b. If they differ, the last edit was one of three, and you take the cheapest:
- replace the letter: up-left + 1;
- delete the last letter of the
aprefix: up + 1; - insert the last letter of the
bprefix: left + 1.
Row k, column k is 2. The letters match, so it copies ca → bac, which is 2: replace c with b, then insert c. In the bottom-right cell, e and k differ. The cheapest option is 2 + 1, for example deleting e from the cell above.
So cake → back takes 3 edits: replace c with b, insert c, delete e. The table has (m + 1) × (n + 1) cells for words of length m and n, and each takes O(1). That is O(m·n) time and memory.
Common mistakes
- Filling row 0 and column 0 with zeros. Then
edit_distance("", "shoe")returns 0, though it needs 4 inserts. - Adding 1 even when the letters match. Then
edit_distance("cake", "cake")returns 4 instead of 0. - Comparing
a[i]withb[j]. Rowistands for the firstiletters, so its last letter isa[i - 1]. Witha[i]you compare the wrong letters, and at the last columnb[j]runs past the end:IndexError. - Counting the positions where the letters differ. That allows only replaces.
cartandchartdiffer at 3 of the first 4 positions, but one insert fixes them.
Follow-up questions
- "Can you use less memory?" Yes. Each row needs only the row above it, so keep two rows. Memory drops to O(n), or O(min(m, n)) if the shorter word goes in the columns. Time stays O(m·n). With only two rows you can't walk back to list the edits.
- "How do you list the actual edits?" Start at the bottom-right cell and walk back. At each cell, move to a neighbour that explains its value: up-left for a match or a replace, up for a delete, left for an insert. For
cake→back, one path gives replace c with b, insert c, delete e. - "A user types
shoseforshoes. Why is the distance 2?" Swapping two neighbouring letters costs two replaces. Add a swap rule: if the last two letters are swapped, also try the cell two up and two left, plus 1. Thenshose→shoescosts 1. This is optimal string alignment. Full Damerau-Levenshtein also lets you insert between swapped letters:ca→ac→abccosts 2, but 3 with the simple rule.
What a strong answer covers
Defines the cell in words before coding, including the empty-prefix row and column. Explains the match case and the three edit cases. Gives O(m·n) time, and cuts memory to two rows when asked.
Open in interactive practice deck →