72. Edit Distance

Description

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character

  2. Delete a character

  3. Replace a character

Constraints

Approach

Levenshtein distance

Examples

Input: word1 = "horse", word2 = "ros"

Output: 3

Explanation:

horse -> rorse (replace 'h' with 'r')

rorse -> rose (remove 'r')

rose -> ros (remove 'e')

Solutions

/**
 * Time complexity : O(mn) as it follows quite straightforward for the inserted loops.
 * Space complexity : O(mn) since at each step we keep the results of all 
 *    previous computations.
 */

class Solution {
    public int minDistance(String word1, String word2) {
        int w1Len = word1.length();
        int w2Len = word2.length();
        // if one of the strings is empty
        if(w1Len * w2Len == 0) return w1Len + w2Len;
        
        int[][] dp = new int[w2Len+1][w1Len+1];
        // init boundaries
        for(int i = 0; i <= w1Len; i++) {
            dp[0][i] = i;
        }
        for(int i = 0; i <= w2Len; i++) {
            dp[i][0] = i;
        }
        // DP compute
        for(int i = 1; i <= w2Len; i++) {
            for(int j = 1; j <= w1Len; j++) {
                if(word2.charAt(i-1) == word1.charAt(j-1)) {
                    dp[i][j] = dp[i-1][j-1];
                } else {
                    dp[i][j] = Math.min(dp[i-1][j-1], 
                                    Math.min(dp[i-1][j], dp[i][j-1])) + 1;
                }
            }
        }
        return dp[w2Len][w1Len];
    }
}

Follow up

  • Given two words word1 and word2, find and print the minimum number of operations required to convert word1 to word2.

Last updated

Was this helpful?