Edit Distance
Medium
Topics
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
from
delete
delete
replace
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
from
replace
replace
replace
replace
replace
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
- Base cases: converting to/from an empty string costs its length.
- If chars equal: dp[i][j] = dp[i-1][j-1].
- 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] = ianddp[0][j] = jare 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]import java.util.*;
class Solution {
public int minDistance(String s, String t) {
int m=s.length(),n=t.length();
int[][] dp=new int[m+1][n+1];
for(int i=0;i<=m;i++)dp[i][0]=i;
for(int j=0;j<=n;j++)dp[0][j]=j;
for(int i=1;i<=m;i++)for(int j=1;j<=n;j++)dp[i][j]=s.charAt(i-1)==t.charAt(j-1)?dp[i-1][j-1]:1+Math.min(dp[i-1][j],Math.min(dp[i][j-1],dp[i-1][j-1]));
return dp[m][n];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minDistance(string s, string t) {
int m=s.size(),n=t.size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
for(int i=0;i<=m;i++)dp[i][0]=i;
for(int j=0;j<=n;j++)dp[0][j]=j;
for(int i=1;i<=m;i++)for(int j=1;j<=n;j++)dp[i][j]=s[i-1]==t[j-1]?dp[i-1][j-1]:1+min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]});
return dp[m][n];
}
};/**
* @param {string} s
* @param {string} t
* @return {number}
*/ var minDistance = function(s, t) {
const m=s.length,n=t.length,dp=[];
for(let i=0;i<=m;i++) {
dp.push(new Array(n+1).fill(0));
dp[i][0]=i;
}
for(let j=0;j<=n;j++)dp[0][j]=j;
for(let i=1;i<=m;i++)for(let j=1;j<=n;j++)dp[i][j]=s[i-1]===t[j-1]?dp[i-1][j-1]:1+Math.min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]);
return dp[m][n];
};