72. Edit Distance

Explanation

To solve this problem, we can use dynamic programming. We can define a 2D array dp, where dp[i][j] represents the minimum number of operations required to convert the substring word1[0...i-1] to word2[0...j-1].

We can fill in the dp array iteratively, considering the following cases:

  1. If the characters at index i in word1 and index j in word2 are the same, then no operation is needed, and dp[i][j] = dp[i-1][j-1].
  2. If the characters are different, we have three options:
    • Insert a character: dp[i][j] = dp[i][j-1] + 1
    • Delete a character: dp[i][j] = dp[i-1][j] + 1
    • Replace a character: dp[i][j] = dp[i-1][j-1] + 1

The final answer will be dp[word1.length()][word2.length()].

class Solution {
    public int minDistance(String word1, String word2) {
        int m = word1.length();
        int n = word2.length();
        int[][] dp = new int[m + 1][n + 1];

        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0) {
                    dp[i][j] = j;
                } else if (j == 0) {
                    dp[i][j] = i;
                } else 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][j - 1], Math.min(dp[i - 1][j], dp[i - 1][j - 1]));
                }
            }
        }

        return dp[m][n];
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.