Edit Distance
Find the fewest letter changes that turn one word into another
DSA, Medium, 2-D DP
Which structure or algorithm, and what does it cost.
You get two words, start and goal. One edit is one of these: add a letter anywhere, delete a letter, or replace a letter with a different one. Return the smallest number of edits that turn start into goal.
Examples
Constraints
- 0 <= length of
start,goal<= 800. - Both words use lowercase English letters.
Your answer must contain
- The simple method and why it is too slow; the better method; the best method and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n * m) time and O(m) memory, where n and m are the two lengths.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Compare the last letters of the two words. If they match, can you ignore them? If not, which edits could fix the end?
Hint 2 the approach
Define the cost for every pair of prefixes. A longer pair is built from three shorter pairs: after an add, a delete or a replace.
Hint 3 the key step
Row 0 and column 0 are the cost of building from or down to an empty word. On a mismatch, which three shorter cells could the last edit come from?
Walkthrough
Full walkthrough brute force to best
Brute force
Try all three edits at every mismatch and recurse. The number of calls grows exponentially with the lengths, so words of about 20 letters already take too long.
Better method
Recursion with memory. Let cost(i, j) be the fewest edits that turn the first i letters of start into the first j letters of goal. If the last letters match, it is cost(i - 1, j - 1). Otherwise it is 1 plus the least of cost(i - 1, j) for a delete, cost(i, j - 1) for an add and cost(i - 1, j - 1) for a replace. Store each pair. Each pair costs a single step, so both time and memory grow as O(n * m).
Best method
Fill the same rule as a table. Cell (i, j) holds the fewest edits that turn the first i letters of start into the first j letters of goal. Row 0 is 0, 1, 2, and so on, because adding j letters to an empty word costs j. Column 0 counts up the same way, as deletes. If the two newest letters match, they need no edit, so the cell copies the diagonal cell. If they differ, the last step was a delete, an add or a replace, so the cell is 1 plus the least of the cell above, the cell to the left and the diagonal cell. Only the previous row is ever read, so two lists are enough. The answer is the last cell.
Hand trace
Run on start = "goat", goal = "boats". Columns are the prefixes "", b, bo, boa, boat, boats. The first row is [0, 1, 2, 3, 4, 5]. After g: [1, 1, 2, 3, 4, 5]. After o: [2, 2, 1, 2, 3, 4]. After a: [3, 3, 2, 1, 2, 3]. After t: [4, 4, 3, 2, 1, 2]. The last value is 2.
Code
def min_edits(start, goal):
prev = list(range(len(goal) + 1)) # prev[j]: edits from the empty word to goal[:j]
for i, a in enumerate(start, 1):
cur = [i]
for j, b in enumerate(goal, 1):
if a == b:
cur.append(prev[j - 1])
else:
cur.append(1 + min(prev[j - 1], prev[j], cur[j - 1]))
prev = cur
return prev[-1]Time and memory
O(n * m) time, one step per cell. O(m) memory for two rows.
Common mistakes
- Counting a replace as two edits, a delete and an add. Example 1 then gives 3, not 2.
- Leaving out row 0 and column 0. An empty word then costs 0, and example 3 returns 0 instead of 3.
- Copying the diagonal cell even when the letters differ. That drops the cost of the replace.