79. Edit Distance
Return the minimum number of operations (insert, delete or replace a character) needed to turn word1 into word2.
Example 1
Input:
word1 = "horse", word2 = "ros"Output:
3Explanation: horse → rorse (replace) → rose (delete) → ros (delete).
Example 2
Input:
word1 = "kitten", word2 = "sitting"Output:
3Hint 1
dp[i][j] = edits to turn the first i chars of word1 into the first j chars of word2.
Hint 2
Each of the three operations corresponds to one neighbouring cell.
Approach 1: 2-D DP (Levenshtein) ✅
Fill the table from the empty-prefix base cases.
⏱ Time O(m · n)💾 Space O(m · n)
Reference solution for 2-D DP (Levenshtein) (time O(m · n), space O(m · n)). Each solution passes every test in all four languages.
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
dp = [[0] * (n + 1) for _ in range(m + 1)] # dp[i][j]: edits for word1[:i] -> word2[:j]
for i in range(m + 1): dp[i][0] = i # delete everything
for j in range(n + 1): dp[0][j] = j # insert everything
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], # delete
dp[i][j - 1], # insert
dp[i - 1][j - 1]) # replace
return dp[m][n]class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length(), n = word2.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] = word1.charAt(i - 1) == word2.charAt(j - 1) ? dp[i - 1][j - 1]
: 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1]));
return dp[m][n];
}
}class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size(), n = word2.size();
vector<vector<int>> dp(m + 1, vector<int>(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] = word1[i - 1] == word2[j - 1] ? dp[i - 1][j - 1]
: 1 + min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]});
return dp[m][n];
}
};function minDistance(word1, word2) {
const m = word1.length, n = word2.length;
const dp = Array.from({ length: m + 1 }, (_, i) => Array.from({ length: n + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
for (let i = 1; i <= m; i++)
for (let j = 1; j <= n; j++)
dp[i][j] = word1[i - 1] === word2[j - 1] ? dp[i - 1][j - 1]
: 1 + Math.min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]);
return dp[m][n];
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Dynamic Programming (2-D).
Run your code to see results here.