Edit Distance


Problem Statement :


Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

You have the following three operations permitted on a word:

Insert a character
Delete a character
Replace a character
 

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation: 
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation: 
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
 

Constraints:

0 <= word1.length, word2.length <= 500
word1 and word2 consist of lowercase English letters.



Solution :



title-img


                            Solution in C :

#define min(a,b,c) ((a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c)))

int minDistance(char * word1, char * word2){    
    int len1 = strlen(word1);
    int len2 = strlen(word2);
	
    if(len1 == 0)
        return len2;
    if(len2 == 0)
        return len1;
    
    int i, j;
    int** table = (int**)malloc(len1 * sizeof(int*));
    for(i = 0; i < len1; i++){
        table[i] = (int*)malloc(len2 * sizeof(int));
    }
    
    if(word1[0] == word2[0])
        table[0][0] = 0;
    else
        table[0][0] = 1;
    // 第一列
        for(i = 1; i < len2; i++){
            if(word1[0] == word2[i])
                table[0][i] = i;
            else
                table[0][i] = table[0][i-1] + 1;
        }
    //第一行
        for(i = 1; i < len1; i++){
            if(word2[0] == word1[i])
                table[i][0] = i;
            else
                table[i][0] = table[i-1][0] + 1;
        }
    //處理其他
    for(i = 1; i < len1; i++){
        for(j = 1; j < len2; j++){
            if(word1[i] == word2[j])
                table[i][j] = table[i-1][j-1];
            
            else 
                 table[i][j] = 1 + min(table[i-1][j], table[i][j-1], table[i-1][j-1]); 
        }
    }
    
    int ans = table[len1-1][len2-1];
    for(i = 0; i < len1; i++){
        free(table[i]);
    }
    free(table);
    
    return ans;

}
                        


                        Solution in C++ :

class Solution {
public:
     int minDistance(string word1, string word2) {
        
        int m=word1.length(),n=word2.length();
        
        int dp[m+1][n+1];
        
        for(int i=0;i<=m;i++)
            dp[i][0]=i;
        
        for(int i=0;i<=n;i++)
            dp[0][i]=i;
        
        for(int i=1;i<=m;i++)
        {
            for(int j=1;j<=n;j++)
            {
                if(word1[i-1]==word2[j-1])
                    dp[i][j]=dp[i-1][j-1];
                else{
                    dp[i][j] = 1+ min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1]));
                }
            }
        }
        return dp[m][n];
    }
};
                    


                        Solution in Java :

class Solution {
    public int minDistance(String word1, String word2) {
        if (word1 == null || word2 == null) {
            throw new IllegalArgumentException("Input strings are null");
        }

        int insertCost = 1;
        int deleteCost = 1;
        int replaceCost = 1;
        int l1 = word1.length();
        int l2 = word2.length();

        if (l1 == 0) {
            return l2 * insertCost;
        }
        if (l2 == 0) {
            return l1 * deleteCost;
        }
        // Bellow condition can be used only if all three costs are same.
        if (l1 > l2) {
            return minDistance(word2, word1);
        }

        int[] dp = new int[l1 + 1];
        // Setting DP array for 0th column of 2D DP array. Here l2 is blank, thus we
        // have to delete everything in l1.
        for (int i = 1; i <= l1; i++) {
            dp[i] = dp[i - 1] + deleteCost;
        }

        for (int j = 1; j <= l2; j++) {
            int prev = dp[0];
            dp[0] += insertCost; // l1 is blank, Inserting l2 chars in l1.
            char c2 = word2.charAt(j - 1);
            for (int i = 1; i <= l1; i++) {
                char c1 = word1.charAt(i - 1);
                int temp = dp[i];
                // Both chars are same, so the distance will also remain same as dp[i-1][j-1]
                if (c1 == c2) {
                    dp[i] = prev;
                } else {
                    // Replace l1[i - 1] by l2[j - 1] ==> dp[i][j] = dp[i - 1][j - 1] + 1
                    // Delete l1[i-1] from l1[0..i-1] ==> dp[i-1][j] + 1
                    // Insert l2[j-1] into l1[0..i-1] ==> dp[i][j-1] + 1
                    dp[i] = Math.min(prev + replaceCost, Math.min(dp[i - 1] + deleteCost, dp[i] + insertCost));
                }
                prev = temp;
            }
        }

        return dp[l1];
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def minDistance(self, s1: str, s2: str) -> int:

        @lru_cache(maxsize=None)
        def f(i, j):
            if i == 0 and j == 0: return 0
            if i == 0 or j == 0: return i or j
            if s1[i - 1] == s2[j - 1]:
                return f(i - 1, j - 1)
            return min(1 + f(i, j - 1), 1 + f(i - 1, j), 1 + f(i - 1, j - 1))

        m, n = len(s1), len(s2)
        return f(m, n)
                    


View More Similar Problems

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution →

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution →

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution →

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution →

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →