Edit Distance
Given two strings word1word2word1word2
Example 1
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation: horse → rorse (replace 'h' with 'r') → rose (delete 'r') → ros (delete 'e').
Output: 3
Explanation: horse → rorse (replace 'h' with 'r') → rose (delete 'r') → ros (delete 'e').
Example 2
Input: word1 = "intention", word2 = "execution"
Output: 5
Output: 5
Solution Approach - 2D DP
We build a 2D DP table where dp[i][j]iword1jword2
- Base cases:
(delete all characters) anddp[i][0] = i (insert all characters).dp[0][j] = j - If characters match:
.dp[i][j] = dp[i-1][j-1] - If characters differ:
representing delete, insert, and replace respectively.dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) - The answer is
where m and n are the lengths of the two words.dp[m][n]
Java
public class EditDistance {
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++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + Math.min(dp[i - 1][j - 1],
Math.min(dp[i - 1][j], dp[i][j - 1]));
}
}
}
return dp[m][n];
}
}
Complexity Analysis:
Time complexity: O(m * n) where m and n are the lengths of the two words.
Space complexity: O(m * n) for the 2D DP table; can be optimized to O(min(m,n)) using two rows.