The fewest inserts, deletes and replaces to turn one word into another. Fill a table where each cell takes the cheapest of three neighbours.
▼The problem
Given two words, return the fewest operations that turn word1 into word2, where an operation inserts a letter, deletes a letter, or replaces one letter with another.
Example: "horse" → "ros" takes 3 edits: replace H with R (rorse), delete the middle R (rose), delete E (ros).
def min_distance(word1, word2):
m, n = len(word1), len(word2)
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 word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j - 1],
dp[i - 1][j],
dp[i][j - 1])
return dp[m][n]TRY IT ON LEETCODE ▶The solution
def min_distance(word1, word2):
m, n = len(word1), len(word2)
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 word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j - 1],
dp[i - 1][j],
dp[i][j - 1])
return dp[m][n]Transcript
Edit Distance. Given two words, find the fewest edits that turn the first into the second. An edit inserts, deletes, or replaces one letter.
Take horse and R, O, S. Replace the H with an R, delete the middle R, and delete the E. Three edits, and nothing shorter works.
The naive way tries all three edits at every mismatch, recursively. Each call branches three ways, so the work grows exponentially. These two short words already take seventy-seven calls, solving the same small pieces again and again.
Instead, solve each piece once, in a table. Cell i, j holds the fewest edits to turn the first i letters of horse into the first j letters of R, O, S. From nothing, you insert every letter, so the top row counts up. To reach nothing, you delete, so the left column does too.
For any other cell, compare the two last letters. If they match, they're free: copy the cell up and to the left. If they differ, pay one, plus the cheapest of three neighbors. Up left means replace. Up means delete. Left means insert.
In code, fill the first row and column, then two loops visit every other cell. A match copies the diagonal; otherwise, it's one plus the smallest of three. The answer sits in the bottom right corner.
Let's fill it. H against R: different, so one plus the smallest of zero, one and one: one. O against O: a match, so copy the diagonal: one. Row by row, the table fills until the corner says three. Now trace back: delete E, keep S, delete R, keep O, and replace H with R.
With m and n letters, that's about m times n cells, each in constant time, so the time is O of m times n. The table takes the same space, but each row only reads the one above, so a single row is enough.
Small pieces first, then build up. That's Edit Distance.