Edit Distance
Find the fewest single-letter inserts, deletes and replaces that turn one word into another.
The problem
You get two words, word1 and word2. In one operation you may insert a letter, delete a letter or replace a letter in word1. Return the fewest operations that turn word1 into word2.
Input word1 = "biryani", word2 = "briyani"
Output 2
Replace the i after b with r and the r after it with i. There is no swap operation, so a swap costs 2.
Input word1 = "tea", word2 = "eat"
Output 2
Delete the t at the front and insert a t at the end.
Key constraint: Both words have at most 500 letters, so a table of about 250,000 cells is fine.
How to spot the pattern
- You transform one sequence into another with a small set of edit operations.
- Every operation can be pictured at the end of a prefix, so prefixes give smaller versions of the problem.
The idea
State: dist[i][j] is the fewest edits that turn the first i letters of word1 into the first j letters of word2. If the last letters match, they need no edit: dist[i][j] = dist[i - 1][j - 1]. Otherwise the last operation was a delete (dist[i - 1][j]), an insert (dist[i][j - 1]) or a replace (dist[i - 1][j - 1]), so take 1 plus the smallest of the three.
Brute force: Recursively try all three operations at every mismatch without saving results, which takes exponential time.
Step by step
- 1Make a table of size
(m + 1) x (n + 1)and fill its edges:dist[i][0] = i(delete everything) anddist[0][j] = j(insert everything). - 2Fill the rest row by row.
- 3If
word1[i - 1] == word2[j - 1], copydist[i - 1][j - 1]. - 4Otherwise set
dist[i][j]to 1 plus the minimum ofdist[i - 1][j],dist[i][j - 1]anddist[i - 1][j - 1]. - 5Return
dist[m][n].
See the pattern move
The 2d dynamic programming pattern on a small example. Step through it, or press play.
Code
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
# dist[i][j] = fewest edits to turn the first i letters of word1 into the first j of word2
dist = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dist[i][0] = i # delete all i letters
for j in range(n + 1):
dist[0][j] = j # insert all j letters
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i - 1] == word2[j - 1]:
dist[i][j] = dist[i - 1][j - 1] # last letters match: no edit needed
else:
dist[i][j] = 1 + min(
dist[i - 1][j], # delete word1[i - 1]
dist[i][j - 1], # insert word2[j - 1]
dist[i - 1][j - 1], # replace word1[i - 1] with word2[j - 1]
)
return dist[m][n]Complexity
Time
O(m * n)
Space
O(m * n)
One cell per pair of prefixes, each filled in O(1).
Watch out for
- Leaving the first row and column at 0: turning a prefix into an empty word still costs one delete per letter.
- Adding 1 even when the last letters match; a match is free.
Follow-up questions
Can you use less memory?
Each row needs only the row above it and the cell to its left, so two rows give O(n) space.
How would you list the actual edits?
Walk back from dist[m][n], each time moving to the neighbor that produced the value, and record a delete, insert, replace or free match for each move.
In Hinglish
Aakhri letters same hain toh bina kharche diagonal pe jao. Alag hain toh delete, insert aur replace teeno try karo aur sabse saste mein 1 jodo.