Edit Distance

Medium

Topics
StringDynamic Programming

Given two strings word1 and word2, return the minimum number of operations (insert, delete, or replace a character) to convert word1 into word2.

Example 1

fromhorse
deletehors
deletehos
replaceros
the character that changed
One allowed edit per row, turning the first string into the last: a character inserted, deleted, or replaced. The answer counts the rows of edits, 3 here — no shorter sequence exists.
Each row is the string after one edit; the shaded cell is where that edit landed.
Input:  word1 = "horse", word2 = "ros"
Output: 3

Example 2

fromintention
replaceinteution
replaceintcution
replaceinecution
replaceixecution
replaceexecution
the character that changed
Input:  word1 = "intention", word2 = "execution"
Output: 5

Constraints

  • 0 <= word1.length, word2.length <= 500
  • Inputs consist of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

dp[i][j] is the edit distance between the first i chars of word1 and first j of word2. If the current chars match, no new op is needed; otherwise you pay 1 for the cheapest of insert, delete, or replace.

Approach

  1. Base cases: converting to/from an empty string costs its length.
  2. If chars equal: dp[i][j] = dp[i-1][j-1].
  3. Else 1 + min(dp[i-1][j] delete, dp[i][j-1] insert, dp[i-1][j-1] replace).

Dry Run

s = "horse"  ->  t = "ros"
dp[i][j] = cost of turning the first i characters of s into the first j of t.
         ""   r   o   s
  ""      0   1   2   3
  h       1   1   2   3
  o       2   2   1   2
  r       3   2   2   2
  s       4   3   3   2
  e       5   4   4   3
answer 3   --  replace h with r, delete the r, delete the e
The two base edges are not decoration. dp[i][0] = i is the cost of deleting all i
characters; dp[0][j] = j is the cost of inserting all j. Drop the first row and
"abc" against "" returns 0 instead of 3, and this input quietly returns 2.
On a mismatch the `1 +` applies to the minimum of THREE neighbours, and each one
is a different edit: dp[i-1][j] is a delete, dp[i][j-1] an insert, dp[i-1][j-1] a
replace. Leaving the diagonal out of the min forbids substitution without saying
so, and horse/ros then costs 4 -- two single-character edits where one
replacement would do.
On a match the cost carries straight through from the diagonal with no `1 +` at
all. Row o, column o is 1: the o is free, and the 1 is the h that still has to
become an r.

Complexity

  • Time — O(m*n): fill the full table.
  • Space — O(m*n): the DP grid.

Common Pitfalls

  • Both base edges have to be seeded. dp[i][0] = i and dp[0][j] = j are the cost of deleting everything and of inserting everything; dropping the row leaves zeros, and a non-empty string against an empty one returns 0 instead of 3.
  • On a mismatch the 1 + applies to the minimum of all three neighbours -- delete, insert, replace. Leaving the diagonal out of the min is the common slip, and it silently forbids substitution.

Full Solution — all languages

class Solution:
    def minDistance(self, s, t):
        m,n=len(s),len(t)
        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):
                dp[i][j]=dp[i-1][j-1] if s[i-1]==t[j-1] else 1+min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])
        return dp[m][n]
SensAI
Beta
Tap the mic to stop voice mode