Edit Distance

Edit Distance

Edit Distance - DP on Strings

https://www.codingninjas.com/studio/problems/edit-distance_630420

My approach:

Code:

Memoization:

int helper(string str1, string str2, int i, int j, vector<vector<int>> &dp){

    if(j==0){
        return i;
    }
    if(i==0){
        return j;
    }

    if(dp[i][j]!=-1){
        return dp[i][j];
    }

    int ans;
    if(str1[i-1]==str2[j-1]){
        ans = helper(str1,str2,i-1,j-1,dp);
    }else{
        int insert = 1+helper(str1,str2,i,j-1,dp);
        int del = 1+helper(str1,str2,i-1,j,dp);
        int replace = 1+helper(str1,str2,i-1,j-1,dp);

        ans = min(insert, min(del, replace));
    }

    dp[i][j] = ans;
    return ans;
}

int editDistance(string str1, string str2)
{
    //write you code here
    int n = str1.size();
    int m= str2.size();

    vector<vector<int>> dp(n+1, vector<int>(m+1,-1));
    return helper(str1,str2,n,m,dp);
}

Tabulation:

int editDistance(string str1, string str2)
{
    //write you code here
    int n = str1.size();
    int m= str2.size();

    vector<vector<int>> dp(n+1, vector<int>(m+1,0));

    for(int i=1;i<=n;i++){
        dp[i][0] = i;
    }

    for(int i=1;i<=m;i++){
        dp[0][i] = i;
    }

    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(str1[i-1]==str2[j-1]){
                dp[i][j] = dp[i-1][j-1];
            }else{
                int insert = 1+dp[i][j-1];
                int del = 1+dp[i-1][j];
                int replace = 1+dp[i-1][j-1];

                dp[i][j] = min(insert, min(del, replace));
            }
        }
    }

    return dp[n][m];

}