Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Edit Distance | DP-5

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Given two strings str1 and str2 and below operations that can be performed on str1. Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.  

  1. Insert
  2. Remove
  3. Replace

All of the above operations are of equal cost. 

Examples: 

Input:   str1 = “geek”, str2 = “gesek”
Output:  1
Explanation: We can convert str1 into str2 by inserting a ‘s’.

Input:   str1 = “cat”, str2 = “cut”
Output:  1
Explanation: We can convert str1 into str2 by replacing ‘a’ with ‘u’.

Input:   str1 = “sunday”, str2 = “saturday”
Output:  3
Explanation: Last three and first characters are same.  We basically need to convert “un” to “atur”.  This can be done using below three operations. Replace ‘n’ with ‘r’, insert t, insert a

Recommended Practice

What are the subproblems in this case? 
The idea is to process all characters one by one starting from either from left or right sides of both strings. 
Let us traverse from right corner, there are two possibilities for every pair of character being traversed.  

m: Length of str1 (first string)
n: Length of str2 (second string)
  1. If last characters of two strings are same, nothing much to do. Ignore last characters and get count for remaining strings. So we recur for lengths m-1 and n-1.
  2. Else (If last characters are not same), we consider all operations on ‘str1’, consider all three operations on last character of first string, recursively compute minimum cost for all three operations and take minimum of three values. 
    1. Insert: Recur for m and n-1
    2. Remove: Recur for m-1 and n
    3. Replace: Recur for m-1 and n-1

Below is implementation of above Naive recursive solution.

C




#include <stdio.h>
#include <string.h>
 
// Utility function to find minimum of three numbers
int min(int x, int y, int z)
{
    return x < y ? (x < z ? x : z) : (y < z ? y : z);
}
 
int editDist(char* str1, char* str2, int m, int n)
{
    // If first string is empty, the only option is to
    // insert all characters of second string into first
    if (m == 0)
        return n;
 
    // If second string is empty, the only option is to
    // remove all characters of first string
    if (n == 0)
        return m;
 
    // If last characters of two strings are same, nothing
    // much to do. Ignore last characters and get count for
    // remaining strings.
    if (str1[m - 1] == str2[n - 1])
        return editDist(str1, str2, m - 1, n - 1);
 
    // If last characters are not same, consider all three
    // operations on last character of first string,
    // recursively compute minimum cost for all three
    // operations and take minimum of three values.
    return 1
           + min(
               editDist(str1, str2, m, n - 1), // Insert
               editDist(str1, str2, m - 1, n), // Remove
               editDist(str1, str2, m - 1, n - 1) // Replace
           );
}
 
// Driver code
int main()
{
    // your code goes here
    char str1[] = "sunday";
    char str2[] = "saturday";
    int m = strlen(str1);
    int n = strlen(str2);
 
    printf("%d", editDist(str1, str2, m, n));
 
    return 0;
}

C++




// A Naive recursive C++ program to find minimum number
// operations to convert str1 to str2
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to find minimum of three numbers
int min(int x, int y, int z) { return min(min(x, y), z); }
 
int editDist(string str1, string str2, int m, int n)
{
    // If first string is empty, the only option is to
    // insert all characters of second string into first
    if (m == 0)
        return n;
 
    // If second string is empty, the only option is to
    // remove all characters of first string
    if (n == 0)
        return m;
 
    // If last characters of two strings are same, nothing
    // much to do. Ignore last characters and get count for
    // remaining strings.
    if (str1[m - 1] == str2[n - 1])
        return editDist(str1, str2, m - 1, n - 1);
 
    // If last characters are not same, consider all three
    // operations on last character of first string,
    // recursively compute minimum cost for all three
    // operations and take minimum of three values.
    return 1
           + min(editDist(str1, str2, m, n - 1), // Insert
                 editDist(str1, str2, m - 1, n), // Remove
                 editDist(str1, str2, m - 1,
                          n - 1) // Replace
             );
}
 
// Driver code
int main()
{
    // your code goes here
    string str1 = "sunday";
    string str2 = "saturday";
 
    cout << editDist(str1, str2, str1.length(),
                     str2.length());
 
    return 0;
}

Java




// A Naive recursive Java program to find minimum number
// operations to convert str1 to str2
class EDIST {
    static int min(int x, int y, int z)
    {
        if (x <= y && x <= z)
            return x;
        if (y <= x && y <= z)
            return y;
        else
            return z;
    }
 
    static int editDist(String str1, String str2, int m,
                        int n)
    {
        // If first string is empty, the only option is to
        // insert all characters of second string into first
        if (m == 0)
            return n;
 
        // If second string is empty, the only option is to
        // remove all characters of first string
        if (n == 0)
            return m;
 
        // If last characters of two strings are same,
        // nothing much to do. Ignore last characters and
        // get count for remaining strings.
        if (str1.charAt(m - 1) == str2.charAt(n - 1))
            return editDist(str1, str2, m - 1, n - 1);
 
        // If last characters are not same, consider all
        // three operations on last character of first
        // string, recursively compute minimum cost for all
        // three operations and take minimum of three
        // values.
        return 1
            + min(editDist(str1, str2, m, n - 1), // Insert
                  editDist(str1, str2, m - 1, n), // Remove
                  editDist(str1, str2, m - 1,
                           n - 1) // Replace
              );
    }
 
    // Driver Code
    public static void main(String args[])
    {
        String str1 = "sunday";
        String str2 = "saturday";
 
        System.out.println(editDist(
            str1, str2, str1.length(), str2.length()));
    }
}
/*This code is contributed by Rajat Mishra*/

Python3




# A Naive recursive Python program to find minimum number
# operations to convert str1 to str2
 
 
def editDistance(str1, str2, m, n):
 
    # If first string is empty, the only option is to
    # insert all characters of second string into first
    if m == 0:
        return n
 
    # If second string is empty, the only option is to
    # remove all characters of first string
    if n == 0:
        return m
 
    # If last characters of two strings are same, nothing
    # much to do. Ignore last characters and get count for
    # remaining strings.
    if str1[m-1] == str2[n-1]:
        return editDistance(str1, str2, m-1, n-1)
 
    # If last characters are not same, consider all three
    # operations on last character of first string, recursively
    # compute minimum cost for all three operations and take
    # minimum of three values.
    return 1 + min(editDistance(str1, str2, m, n-1),    # Insert
                   editDistance(str1, str2, m-1, n),    # Remove
                   editDistance(str1, str2, m-1, n-1)    # Replace
                   )
 
 
# Driver code
str1 = "sunday"
str2 = "saturday"
print (editDistance(str1, str2, len(str1), len(str2)))
 
# This code is contributed by Bhavya Jain

C#




// A Naive recursive C# program to
// find minimum numberoperations
// to convert str1 to str2
using System;
 
class GFG {
    static int min(int x, int y, int z)
    {
        if (x <= y && x <= z)
            return x;
        if (y <= x && y <= z)
            return y;
        else
            return z;
    }
 
    static int editDist(String str1, String str2, int m,
                        int n)
    {
        // If first string is empty, the only option is to
        // insert all characters of second string into first
        if (m == 0)
            return n;
 
        // If second string is empty, the only option is to
        // remove all characters of first string
        if (n == 0)
            return m;
 
        // If last characters of two strings are same,
        // nothing much to do. Ignore last characters and
        // get count for remaining strings.
        if (str1[m - 1] == str2[n - 1])
            return editDist(str1, str2, m - 1, n - 1);
 
        // If last characters are not same, consider all
        // three operations on last character of first
        // string, recursively compute minimum cost for all
        // three operations and take minimum of three
        // values.
        return 1
            + min(editDist(str1, str2, m, n - 1), // Insert
                  editDist(str1, str2, m - 1, n), // Remove
                  editDist(str1, str2, m - 1,
                           n - 1) // Replace
              );
    }
 
    // Driver code
    public static void Main()
    {
        String str1 = "sunday";
        String str2 = "saturday";
        Console.WriteLine(
            editDist(str1, str2, str1.Length, str2.Length));
    }
}
 
// This Code is Contributed by Sam007

PHP




<?php
// A Naive recursive Python program 
// to find minimum number operations
// to convert str1 to str2
function editDistance($str1, $str2,
                      $m, $n)
{
    // If first string is empty,
    // the only option is to insert.
    // all characters of second
    // string into first
    if ($m == 0)
        return $n;
 
    // If second string is empty,
    // the only option is to
    // remove all characters of
    // first string
    if ($n == 0)
        return $m;
 
    // If last characters of two
    // strings are same, nothing
    // much to do. Ignore last
    // characters and get count
    // for remaining strings.
    if ($str1[$m - 1] == $str2[$n - 1])
    {
        return editDistance($str1, $str2,
                            $m - 1, $n - 1);
    }
     
    // If last characters are not same,
    // consider all three operations on
    // last character of first string,
    // recursively compute minimum cost
    // for all three operations and take
    // minimum of three values.
 
    return 1 + min(editDistance($str1, $str2,
                                $m, $n - 1), // Insert
                   editDistance($str1, $str2,
                                $m - 1, $n), // Remove
                   editDistance($str1, $str2,
                                $m - 1, $n - 1)); // Replace
}
 
// Driver Code
$str1 = "sunday";
$str2 = "saturday";
echo editDistance($str1, $str2, strlen($str1),
                                strlen($str2));
 
// This code is contributed
// by Shivi_Aggarwal
?>

Javascript




<script>
 
// Javascript program to
// find minimum numberoperations
// to convert str1 to str2
function min(x, y, z)
{
    if (x <= y && x <= z)
        return x;
    if (y <= x && y <= z)
        return y;
    else
        return z;
}
 
function editDist(str1, str2, m, n)
{
     
    // If first string is empty, the
    // only option is to insert all
    // characters of second string into first
    if (m == 0)
        return n;
 
    // If second string is empty, the only
    // option is to remove all characters
    // of first string
    if (n == 0)
        return m;
 
    // If last characters of two strings are
    // same, nothing much to do. Ignore last
    // characters and get count for remaining
    // strings.
    if (str1[m - 1] == str2[n - 1])
        return editDist(str1, str2, m - 1, n - 1);
 
    // If last characters are not same, consider all
    // three operations on last character of first
    // string, recursively compute minimum cost for all
    // three operations and take minimum of three
    // values.
    return 1 +
    min(editDist(str1, str2, m, n - 1), // Insert
        editDist(str1, str2, m - 1, n), // Remove
        editDist(str1, str2, m - 1, n - 1)); // Replace
}
 
// Driver code
let str1 = "sunday";
let str2 = "saturday";
document.write(editDist(str1, str2, str1.length,
                                    str2.length));
 
// This code is contributed by target_2
 
</script>

Output

3

Time Complexity of above solution is exponential. In worst case, we may end up doing O(3m) operations. The worst case happens when none of characters of two strings match. Below is a recursive call diagram for worst case. 
Auxiliary Space: O(1), because no extra space is utilized.

EditDistance

We can see that many subproblems are solved, again and again, for example, eD(2, 2) is called three times. Since same subproblems are called again, this problem has Overlapping Subproblems property. So Edit Distance problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array that stores results of subproblems.

C




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
// Utility function to find the minimum of three numbers
int min(int x, int y, int z)
{
    if (x <= y && x <= z)
        return x;
    if (y <= x && y <= z)
        return y;
    return z;
}
 
int editDistDP(char* str1, char* str2, int m, int n)
{
    // Create a table to store results of subproblems
    int dp[m + 1][n + 1];
 
    // Fill d[][] in bottom up manner
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            // If first string is empty, only option is to
            // insert all characters of second string
            if (i == 0)
                dp[i][j] = j; // Min. operations = j
 
            // If second string is empty, only option is to
            // remove all characters of second string
            else if (j == 0)
                dp[i][j] = i; // Min. operations = i
 
            // If last characters are same, ignore last char
            // and recur for remaining string
            else if (str1[i - 1] == str2[j - 1])
                dp[i][j] = dp[i - 1][j - 1];
 
            // If the last character is different, consider
            // all possibilities and find the minimum
            else
                dp[i][j]
                    = 1
                      + min(dp[i][j - 1], // Insert
                            dp[i - 1][j], // Remove
                            dp[i - 1][j - 1]); // Replace
        }
    }
 
    return dp[m][n];
}
 
// Driver code
int main()
{
    char str1[] = "sunday";
    char str2[] = "saturday";
 
    int m = strlen(str1);
    int n = strlen(str2);
 
    printf("%d\n", editDistDP(str1, str2, m, n));
 
    return 0;
}

C++




// A Dynamic Programming based C++ program to find minimum
// number operations to convert str1 to str2
#include <bits/stdc++.h>
using namespace std;
 
// Utility function to find the minimum of three numbers
int min(int x, int y, int z) { return min(min(x, y), z); }
 
int editDistDP(string str1, string str2, int m, int n)
{
    // Create a table to store results of subproblems
    int dp[m + 1][n + 1];
 
    // Fill d[][] in bottom up manner
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            // If first string is empty, only option is to
            // insert all characters of second string
            if (i == 0)
                dp[i][j] = j; // Min. operations = j
 
            // If second string is empty, only option is to
            // remove all characters of second string
            else if (j == 0)
                dp[i][j] = i; // Min. operations = i
 
            // If last characters are same, ignore last char
            // and recur for remaining string
            else if (str1[i - 1] == str2[j - 1])
                dp[i][j] = dp[i - 1][j - 1];
 
            // If the last character is different, consider
            // all possibilities and find the minimum
            else
                dp[i][j]
                    = 1
                      + min(dp[i][j - 1], // Insert
                            dp[i - 1][j], // Remove
                            dp[i - 1][j - 1]); // Replace
        }
    }
 
    return dp[m][n];
}
 
// Driver code
int main()
{
    // your code goes here
    string str1 = "sunday";
    string str2 = "saturday";
 
    cout << editDistDP(str1, str2, str1.length(),
                       str2.length());
 
    return 0;
}

Java




// A Dynamic Programming based Java program to find minimum
// number operations to convert str1 to str2
import java.io.*;
 
class EDIST {
    static int min(int x, int y, int z)
    {
        if (x <= y && x <= z)
            return x;
        if (y <= x && y <= z)
            return y;
        else
            return z;
    }
 
    static int editDistDP(String str1, String str2, int m,
                          int n)
    {
        // Create a table to store results of subproblems
        int dp[][] = new int[m + 1][n + 1];
 
        // Fill d[][] in bottom up manner
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                // If first string is empty, only option is
                // to insert all characters of second string
                if (i == 0)
                    dp[i][j] = j; // Min. operations = j
 
                // If second string is empty, only option is
                // to remove all characters of second string
                else if (j == 0)
                    dp[i][j] = i; // Min. operations = i
 
                // If last characters are same, ignore last
                // char and recur for remaining string
                else if (str1.charAt(i - 1)
                         == str2.charAt(j - 1))
                    dp[i][j] = dp[i - 1][j - 1];
 
                // If the last character is different,
                // consider all possibilities and find the
                // minimum
                else
                    dp[i][j]
                        = 1
                          + min(
                              dp[i][j - 1], // Insert
                              dp[i - 1][j], // Remove
                              dp[i - 1][j - 1]); // Replace
            }
        }
 
        return dp[m][n];
    }
 
    // Driver Code
    public static void main(String args[])
    {
        String str1 = "sunday";
        String str2 = "saturday";
        System.out.println(editDistDP(
            str1, str2, str1.length(), str2.length()));
    }
} /*This code is contributed by Rajat Mishra*/

Python3




# A Dynamic Programming based Python program for edit
# distance problem
 
 
def editDistDP(str1, str2, m, n):
    # Create a table to store results of subproblems
    dp = [[0 for x in range(n + 1)] for x in range(m + 1)]
 
    # Fill d[][] in bottom up manner
    for i in range(m + 1):
        for j in range(n + 1):
 
            # If first string is empty, only option is to
            # insert all characters of second string
            if i == 0:
                dp[i][j] = j    # Min. operations = j
 
            # If second string is empty, only option is to
            # remove all characters of second string
            elif j == 0:
                dp[i][j] = i    # Min. operations = i
 
            # If last characters are same, ignore last char
            # and recur for remaining string
            elif str1[i-1] == str2[j-1]:
                dp[i][j] = dp[i-1][j-1]
 
            # If last character are different, consider all
            # possibilities and find minimum
            else:
                dp[i][j] = 1 + min(dp[i][j-1],        # Insert
                                   dp[i-1][j],        # Remove
                                   dp[i-1][j-1])    # Replace
 
    return dp[m][n]
 
 
# Driver code
str1 = "sunday"
str2 = "saturday"
 
print(editDistDP(str1, str2, len(str1), len(str2)))
# This code is contributed by Bhavya Jain

C#




// A Dynamic Programming based
// C# program to find minimum
// number operations to
// convert str1 to str2
using System;
 
class GFG {
    static int min(int x, int y, int z)
    {
        if (x <= y && x <= z)
            return x;
        if (y <= x && y <= z)
            return y;
        else
            return z;
    }
 
    static int editDistDP(String str1, String str2, int m,
                          int n)
    {
        // Create a table to store
        // results of subproblems
        int[, ] dp = new int[m + 1, n + 1];
 
        // Fill d[][] in bottom up manner
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                // If first string is empty, only option is
                // to insert all characters of second string
                if (i == 0)
 
                    // Min. operations = j
                    dp[i, j] = j;
 
                // If second string is empty, only option is
                // to remove all characters of second string
                else if (j == 0)
 
                    // Min. operations = i
                    dp[i, j] = i;
 
                // If last characters are same, ignore last
                // char and recur for remaining string
                else if (str1[i - 1] == str2[j - 1])
                    dp[i, j] = dp[i - 1, j - 1];
 
                // If the last character is different,
                // consider all possibilities and find the
                // minimum
                else
                    dp[i, j] = 1
                               + min(dp[i, j - 1], // Insert
                                     dp[i - 1, j], // Remove
                                     dp[i - 1,
                                        j - 1]); // Replace
            }
        }
 
        return dp[m, n];
    }
 
    // Driver code
    public static void Main()
    {
        String str1 = "sunday";
        String str2 = "saturday";
        Console.Write(editDistDP(str1, str2, str1.Length,
                                 str2.Length));
    }
}
// This Code is Contributed by Sam007

PHP




<?php
// A Dynamic Programming based
// Python program for edit
// distance problem
function editDistDP($str1, $str2,
                    $m, $n)
{
// Fill d[][] in bottom up manner
for ($i = 0; $i <= $m; $i++)
    for ($j = 0; $j <= $n; $j++)
    {
 
        // If first string is empty,
        // only option is to insert
        // all characters of second string
        if ($i == 0)
            $dp[$i][$j] = $j ; // Min. operations = j
 
        // If second string is empty,
        // only option is to remove
        // all characters of second string
        else if($j == 0)
            $dp[$i][$j] = $i; // Min. operations = i
 
        // If last characters are same,
        // ignore last char and recur
        // for remaining string
        else if($str1[$i - 1] == $str2[$j - 1])
            $dp[$i][$j] = $dp[$i - 1][$j - 1];
 
        // If last character are different,
        // consider all possibilities and
        // find minimum
        else
        {
            $dp[$i][$j] = 1 + min($dp[$i][$j - 1],     // Insert
                                  $dp[$i - 1][$j],     // Remove
                                  $dp[$i - 1][$j - 1]); // Replace
        }
    }
}
return $dp[$m][$n] ;
}
 
// Driver Code
$str1 = "sunday";
$str2 = "saturday";
 
echo editDistDP($str1, $str2, strlen($str1),
                              strlen($str2));
 
// This code is contributed
// by Shivi_Aggarwal
?>

Javascript




<script>
 
// A Dynamic Programming based
// Javascript program to find minimum
// number operations to convert str1 to str2
 
function min(x,y,z)
{
    if (x <= y && x <= z)
            return x;
        if (y <= x && y <= z)
            return y;
        else
            return z;
}
 
function editDistDP(str1,str2,m,n)
{
    // Create a table to store results of subproblems
        let dp = new Array(m + 1);
        for(let i=0;i<m+1;i++)
        {
            dp[i]=new Array(n+1);
            for(let j=0;j<n+1;j++)
            {
                dp[i][j]=0;
            }
        }
  
        // Fill d[][] in bottom up manner
        for (let i = 0; i <= m; i++) {
            for (let j = 0; j <= n; j++) {
                // If first string is empty, only option is
                // to insert all characters of second string
                if (i == 0)
                    dp[i][j] = j; // Min. operations = j
  
                // If second string is empty, only option is
                // to remove all characters of second string
                else if (j == 0)
                    dp[i][j] = i; // Min. operations = i
  
                // If last characters are same, ignore last
                // char and recur for remaining string
                else if (str1[i - 1]
                         == str2[j - 1])
                    dp[i][j] = dp[i - 1][j - 1];
  
                // If the last character is different,
                // consider all possibilities and find the
                // minimum
                else
                    dp[i][j] = 1
                               + min(dp[i][j - 1], // Insert
                                     dp[i - 1][j], // Remove
                                     dp[i - 1]
                                       [j - 1]); // Replace
            }
        }
  
        return dp[m][n];
}
 
// Driver Code
let str1 = "sunday";
let str2 = "saturday";
document.write(editDistDP(
str1, str2, str1.length, str2.length));
 
// This code is contributed by unknown2108
 
</script>

Output

3

Time Complexity: O(m x n) 
Auxiliary Space: O(m x n)

Space Complex Solution: In the above-given method we require O(m x n) space. This will not be suitable if the length of strings is greater than 2000 as it can only create 2D array of 2000 x 2000. To fill a row in DP array we require only one row the upper row. For example, if we are filling the i = 10 rows in DP array we require only values of 9th row. So we simply create a DP array of 2 x str1 length. This approach reduces the space complexity. Here is the C++ implementation of the above-mentioned problem

C




#include <math.h>
#include <stdio.h>
#include <string.h>
 
void EditDistDP(char* str1, char* str2)
{
    int len1 = strlen(str1);
    int len2 = strlen(str2);
 
    // Create a DP array to memoize result
    // of previous computations
    int DP[2][len1 + 1];
 
    // To fill the DP array with 0
    memset(DP, 0, sizeof DP);
 
    // Base condition when second string
    // is empty then we remove all characters
    for (int i = 0; i <= len1; i++) {
        DP[0][i] = i;
    }
 
    // Start filling the DP
    // This loop run for every
    // character in second string
    for (int i = 1; i <= len2; i++) {
        // This loop compares the char from
        // second string with first string
        // characters
        for (int j = 0; j <= len1; j++) {
            // if first string is empty then
            // we have to perform add character
            // operation to get second string
            if (j == 0) {
                DP[i % 2][j] = i;
            }
 
            // if character from both string
            // is same then we do not perform any
            // operation . here i % 2 is for bound
            // the row number.
            else if (str1[j - 1] == str2[i - 1]) {
                DP[i % 2][j] = DP[(i - 1) % 2][j - 1];
            }
 
            // if character from both string is
            // not same then we take the minimum
            // from three specified operation
            else {
                DP[i % 2][j]
                    = 1
                      + (int)fmin(
                          DP[(i - 1) % 2][j],
                          fmin(DP[i % 2][j - 1],
                               DP[(i - 1) % 2][j - 1]));
            }
        }
    }
 
    // after complete fill the DP array
    // if the len2 is even then we end
    // up in the 0th row else we end up
    // in the 1th row so we take len2 % 2
    // to get row
    printf("%d\n", DP[len2 % 2][len1]);
}
 
// Driver program
int main()
{
    char str1[] = "food";
    char str2[] = "money";
    EditDistDP(str1, str2);
    return 0;
}

C++




// A Space efficient Dynamic Programming
// based C++ program to find minimum
// number operations to convert str1 to str2
#include <bits/stdc++.h>
using namespace std;
 
void EditDistDP(string str1, string str2)
{
    int len1 = str1.length();
    int len2 = str2.length();
 
    // Create a DP array to memoize result
    // of previous computations
    int DP[2][len1 + 1];
 
    // To fill the DP array with 0
    memset(DP, 0, sizeof DP);
 
    // Base condition when second string
    // is empty then we remove all characters
    for (int i = 0; i <= len1; i++)
        DP[0][i] = i;
 
    // Start filling the DP
    // This loop run for every
    // character in second string
    for (int i = 1; i <= len2; i++) {
        // This loop compares the char from
        // second string with first string
        // characters
        for (int j = 0; j <= len1; j++) {
            // if first string is empty then
            // we have to perform add character
            // operation to get second string
            if (j == 0)
                DP[i % 2][j] = i;
 
            // if character from both string
            // is same then we do not perform any
            // operation . here i % 2 is for bound
            // the row number.
            else if (str1[j - 1] == str2[i - 1]) {
                DP[i % 2][j] = DP[(i - 1) % 2][j - 1];
            }
 
            // if character from both string is
            // not same then we take the minimum
            // from three specified operation
            else {
                DP[i % 2][j] = 1 + min(DP[(i - 1) % 2][j],
                                       min(DP[i % 2][j - 1],
                                           DP[(i - 1) % 2][j - 1]));
            }
        }
    }
 
    // after complete fill the DP array
    // if the len2 is even then we end
    // up in the 0th row else we end up
    // in the 1th row so we take len2 % 2
    // to get row
    cout << DP[len2 % 2][len1] << endl;
}
 
// Driver program
int main()
{
    string str1 = "food";
    string str2 = "money";
    EditDistDP(str1, str2);
    return 0;
}

Java




// A Space efficient Dynamic Programming
// based Java program to find minimum
// number operations to convert str1 to str2
import java.util.*;
class GFG
{
 
static void EditDistDP(String str1, String str2)
{
    int len1 = str1.length();
    int len2 = str2.length();
 
    // Create a DP array to memoize result
    // of previous computations
    int [][]DP = new int[2][len1 + 1];
 
 
    // Base condition when second String
    // is empty then we remove all characters
    for (int i = 0; i <= len1; i++)
        DP[0][i] = i;
 
    // Start filling the DP
    // This loop run for every
    // character in second String
    for (int i = 1; i <= len2; i++)
    {
       
        // This loop compares the char from
        // second String with first String
        // characters
        for (int j = 0; j <= len1; j++)
        {
           
            // if first String is empty then
            // we have to perform add character
            // operation to get second String
            if (j == 0)
                DP[i % 2][j] = i;
 
            // if character from both String
            // is same then we do not perform any
            // operation . here i % 2 is for bound
            // the row number.
            else if (str1.charAt(j - 1) == str2.charAt(i - 1)) {
                DP[i % 2][j] = DP[(i - 1) % 2][j - 1];
            }
 
            // if character from both String is
            // not same then we take the minimum
            // from three specified operation
            else {
                DP[i % 2][j] = 1 + Math.min(DP[(i - 1) % 2][j],
                                       Math.min(DP[i % 2][j - 1],
                                           DP[(i - 1) % 2][j - 1]));
            }
        }
    }
 
    // after complete fill the DP array
    // if the len2 is even then we end
    // up in the 0th row else we end up
    // in the 1th row so we take len2 % 2
    // to get row
    System.out.print(DP[len2 % 2][len1] +"\n");
}
 
// Driver program
public static void main(String[] args)
{
    String str1 = "food";
    String str2 = "money";
    EditDistDP(str1, str2);
}
}
 
// This code is contributed by aashish1995

Python3




# A Space efficient Dynamic Programming
# based Python3 program to find minimum
# number operations to convert str1 to str2
def EditDistDP(str1, str2):
     
    len1 = len(str1)
    len2 = len(str2)
 
    # Create a DP array to memoize result
    # of previous computations
    DP = [[0 for i in range(len1 + 1)]
             for j in range(2)];
 
    # Base condition when second String
    # is empty then we remove all characters
    for i in range(0, len1 + 1):
        DP[0][i] = i
 
    # Start filling the DP
    # This loop run for every
    # character in second String
    for i in range(1, len2 + 1):
         
        # This loop compares the char from
        # second String with first String
        # characters
        for j in range(0, len1 + 1):
 
            # If first String is empty then
            # we have to perform add character
            # operation to get second String
            if (j == 0):
                DP[i % 2][j] = i
 
            # If character from both String
            # is same then we do not perform any
            # operation . here i % 2 is for bound
            # the row number.
            elif(str1[j - 1] == str2[i-1]):
                DP[i % 2][j] = DP[(i - 1) % 2][j - 1]
             
            # If character from both String is
            # not same then we take the minimum
            # from three specified operation
            else:
                DP[i % 2][j] = (1 + min(DP[(i - 1) % 2][j],
                                    min(DP[i % 2][j - 1],
                                  DP[(i - 1) % 2][j - 1])))
             
    # After complete fill the DP array
    # if the len2 is even then we end
    # up in the 0th row else we end up
    # in the 1th row so we take len2 % 2
    # to get row
    print(DP[len2 % 2][len1], "")
 
# Driver code
if __name__ == '__main__':
     
    str1 = "food"
    str2 = "money"
     
    EditDistDP(str1, str2)
 
# This code is contributed by gauravrajput1

C#




// A Space efficient Dynamic Programming
// based C# program to find minimum
// number operations to convert str1 to str2
using System;
class GFG
{
 
static void EditDistDP(String str1, String str2)
{
    int len1 = str1.Length;
    int len2 = str2.Length;
 
    // Create a DP array to memoize result
    // of previous computations
    int [,]DP = new int[2, len1 + 1];
 
 
    // Base condition when second String
    // is empty then we remove all characters
    for (int i = 0; i <= len1; i++)
        DP[0, i] = i;
 
    // Start filling the DP
    // This loop run for every
    // character in second String
    for (int i = 1; i <= len2; i++)
    {
       
        // This loop compares the char from
        // second String with first String
        // characters
        for (int j = 0; j <= len1; j++)
        {
           
            // if first String is empty then
            // we have to perform add character
            // operation to get second String
            if (j == 0)
                DP[i % 2, j] = i;
 
            // if character from both String
            // is same then we do not perform any
            // operation . here i % 2 is for bound
            // the row number.
            else if (str1[j - 1] == str2[i - 1])
            {
                DP[i % 2, j] = DP[(i - 1) % 2, j - 1];
            }
 
            // if character from both String is
            // not same then we take the minimum
            // from three specified operation
            else {
                DP[i % 2, j] = 1 + Math.Min(DP[(i - 1) % 2, j],
                                       Math.Min(DP[i % 2, j - 1],
                                           DP[(i - 1) % 2, j - 1]));
            }
        }
    }
 
    // after complete fill the DP array
    // if the len2 is even then we end
    // up in the 0th row else we end up
    // in the 1th row so we take len2 % 2
    // to get row
    Console.Write(DP[len2 % 2, len1] +"\n");
}
 
// Driver program
public static void Main(String[] args)
{
    String str1 = "food";
    String str2 = "money";
    EditDistDP(str1, str2);
}
}
 
// This code is contributed by aashish1995

Javascript




<script>
// A Space efficient Dynamic Programming
// based Javascript program to find minimum
// number operations to convert str1 to str2
function EditDistDP(str1, str2)
{
    let len1 = str1.length;
    let len2 = str2.length;
  
    // Create a DP array to memoize result
    // of previous computations
    let DP = new Array(2);
    for(let i = 0; i < 2; i++)
    {
        DP[i] = new Array(len1+1);
        for(let j = 0; j < len1 + 1; j++)
            DP[i][j] = 0;
    }
  
  
    // Base condition when second String
    // is empty then we remove all characters
    for (let i = 0; i <= len1; i++)
        DP[0][i] = i;
  
    // Start filling the DP
    // This loop run for every
    // character in second String
    for (let i = 1; i <= len2; i++)
    {
        
        // This loop compares the char from
        // second String with first String
        // characters
        for (let j = 0; j <= len1; j++)
        {
            
            // if first String is empty then
            // we have to perform add character
            // operation to get second String
            if (j == 0)
                DP[i % 2][j] = i;
  
            // if character from both String
            // is same then we do not perform any
            // operation . here i % 2 is for bound
            // the row number.
            else if (str1[j-1] == str2[i-1]) {
                DP[i % 2][j] = DP[(i - 1) % 2][j - 1];
            }
  
            // if character from both String is
            // not same then we take the minimum
            // from three specified operation
            else {
                DP[i % 2][j] = 1 + Math.min(DP[(i - 1) % 2][j],
                                       Math.min(DP[i % 2][j - 1],
                                           DP[(i - 1) % 2][j - 1]));
            }
        }
    }
  
    // after complete fill the DP array
    // if the len2 is even then we end
    // up in the 0th row else we end up
    // in the 1th row so we take len2 % 2
    // to get row
    document.write(DP[len2 % 2][len1] +"<br>");
}
 
// Driver program
let str1 = "food";
let str2 = "money";
EditDistDP(str1, str2);
 
// This code is contributed by patel2127.
</script>

Output

4

Time Complexity: O(m x n) 
Auxiliary Space: O( m )

This is a memoized version of recursion i.e. Top-Down DP:

C




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int min(int x, int y, int z)
{
    if (x < y && x < z)
        return x;
    else if (y < x && y < z)
        return y;
    else
        return z;
}
 
int minDis(char* s1, char* s2, int n, int m)
{
    int dp[n + 1][m + 1];
 
    // Fill dp[][] table in bottom up manner
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= m; j++) {
            // If first string is empty, only option is to
            // insert all characters of second string
            if (i == 0)
                dp[i][j] = j;
            // If second string is empty, only option is to
            // remove all characters of second string
            else if (j == 0)
                dp[i][j] = i;
            // If last characters are same, ignore last char
            // and recur for remaining string
            else if (s1[i - 1] == s2[j - 1])
                dp[i][j] = dp[i - 1][j - 1];
            // If last character are different, consider all
            // possibilities and find minimum
            else
                dp[i][j]
                    = 1
                      + min(dp[i][j - 1], // Insert
                            dp[i - 1][j], // Remove
                            dp[i - 1][j - 1]); // Replace
        }
    }
 
    return dp[n][m];
}
 
int main()
{
    char* str1 = "voldemort";
    char* str2 = "dumbledore";
 
    int n = strlen(str1), m = strlen(str2);
 
    printf("%d", minDis(str1, str2, n, m));
 
    return 0;
}

C++14




#include <bits/stdc++.h>
using namespace std;
int minDis(string s1, string s2, int n, int m,
           vector<vector<int> >& dp)
{
 
    // If any string is empty,
    // return the remaining characters of other string
 
    if (n == 0)
        return m;
 
    if (m == 0)
        return n;
 
    // To check if the recursive tree
    // for given n & m has already been executed
 
    if (dp[n][m] != -1)
        return dp[n][m];
 
    // If characters are equal, execute
    // recursive function for n-1, m-1
 
    if (s1[n - 1] == s2[m - 1]) {
        return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp);
    }
    // If characters are nt equal, we need to
    // find the minimum cost out of all 3 operations.
    // 1. insert 2.delete 3.replace
    else {
        int insert, del, replace; // temp variables
 
        insert = minDis(s1, s2, n, m - 1, dp);
        del = minDis(s1, s2, n - 1, m, dp);
        replace = minDis(s1, s2, n - 1, m - 1, dp);
        return dp[n][m] = 1 + min(insert, min(del, replace));
    }
}
 
// Driver program
int main()
{
 
    string str1 = "voldemort";
    string str2 = "dumbledore";
 
    int n = str1.length(), m = str2.length();
    vector<vector<int> > dp(n + 1, vector<int>(m + 1, -1));
 
    cout << minDis(str1, str2, n, m, dp);
    return 0;
 
    //     This code is a contribution of Bhavneet Singh
}

Java




import java.util.*;
class GFG {
 
    static int minDis(String s1, String s2, int n, int m,
                      int[][] dp)
    {
 
        // If any String is empty,
        // return the remaining characters of other String
        if (n == 0)
            return m;
        if (m == 0)
            return n;
 
        // To check if the recursive tree
        // for given n & m has already been executed
        if (dp[n][m] != -1)
            return dp[n][m];
 
        // If characters are equal, execute
        // recursive function for n-1, m-1
        if (s1.charAt(n - 1) == s2.charAt(m - 1)) {
            return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp);
        }
        // If characters are nt equal, we need to
        // find the minimum cost out of all 3 operations.
        else {
 
            int insert, del, replace; // temp variables
 
            insert = minDis(s1, s2, n, m - 1, dp);
            del = minDis(s1, s2, n - 1, m, dp);
            replace = minDis(s1, s2, n - 1, m - 1, dp);
            return dp[n][m]
                = 1 + Math.min(insert, Math.min(del, replace));
        }
    }
    // Driver program
    public static void main(String[] args)
    {
 
        String str1 = "voldemort";
        String str2 = "dumbledore";
 
        int n = str1.length(), m = str2.length();
        int[][] dp = new int[n + 1][m + 1];
        for (int i = 0; i < n + 1; i++)
            Arrays.fill(dp[i], -1);
        System.out.print(minDis(str1, str2, n, m, dp));
    }
}
 
// This code is contributed by gauravrajput1

Python3




def minDis(s1, s2, n, m, dp) :
          
  # If any string is empty,
  # return the remaining characters of other string         
  if(n == 0) :
      return m       
  if(m == 0) :
      return n
                    
  # To check if the recursive tree
  # for given n & m has already been executed
  if(dp[n][m] != -1)  :
      return dp[n][m];
                   
  # If characters are equal, execute
  # recursive function for n-1, m-1   
  if(s1[n - 1] == s2[m - 1]) :          
    if(dp[n - 1][m - 1] == -1) :
        dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp)
        return dp[n][m]                  
    else :
        dp[n][m] = dp[n - 1][m - 1]
        return dp[n][m]
         
  # If characters are nt equal, we need to          
  # find the minimum cost out of all 3 operations.        
  else :           
    if(dp[n - 1][m] != -1) :  
      m1 = dp[n - 1][m]     
    else :
      m1 = minDis(s1, s2, n - 1, m, dp)
              
    if(dp[n][m - 1] != -1) :               
      m2 = dp[n][m - 1]           
    else :
      m2 = minDis(s1, s2, n, m - 1, dp)  
    if(dp[n - 1][m - 1] != -1) :   
      m3 = dp[n - 1][m - 1]   
    else :
      m3 = minDis(s1, s2, n - 1, m - 1, dp)
     
    dp[n][m] = 1 + min(m1, min(m2, m3))
    return dp[n][m]
     
    # Driver code
str1 = "voldemort"
str2 = "dumbledore"
    
n = len(str1)
m = len(str2)
dp = [[-1 for i in range(m + 1)] for j in range(n + 1)]
              
print(minDis(str1, str2, n, m, dp))
 
# This code is contributed by divyesh072019.

C#




using System;
using System.Collections.Generic;
class GFG {
 
  static int minDis(string s1, string s2, int n,
                    int m, List<List<int>> dp)
  {
 
    // If any string is empty,
    // return the remaining characters of other string
    if(n == 0)  
      return m;
 
    if(m == 0)   
      return n;
 
    // To check if the recursive tree
    // for given n & m has already been executed
    if(dp[n][m] != -1) 
      return dp[n][m];
 
    // If characters are equal, execute
    // recursive function for n-1, m-1
    if(s1[n - 1] == s2[m - 1])
    {          
      if(dp[n - 1][m - 1] == -1)
      {              
        return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp);          
      }       
      else
        return dp[n][m] = dp[n - 1][m - 1];  
    }
 
 
    // If characters are nt equal, we need to
    // find the minimum cost out of all 3 operations.
    else
    {          
      int m1, m2, m3;        // temp variables  
 
      if(dp[n - 1][m] != -1)
      {   
        m1 = dp[n - 1][m];     
      }          
      else
      {  
        m1 = minDis(s1, s2, n - 1, m, dp);     
      }           
 
      if(dp[n][m - 1] != -1)
      {               
        m2 = dp[n][m - 1];           
      }           
      else
      {   
        m2 = minDis(s1, s2, n, m - 1, dp);     
      }                                  
 
      if(dp[n - 1][m - 1] != -1)
      {   
        m3 = dp[n - 1][m - 1];     
      }  
      else
      {  
        m3 = minDis(s1, s2, n - 1, m - 1, dp);      
      }    
      return dp[n][m] = 1+ Math.Min(m1, Math.Min(m2, m3));       
    }
 
  }
 
  // Driver code
  static void Main()
  {
    string str1 = "voldemort";
    string str2 = "dumbledore";
 
    int n = str1.Length, m = str2.Length;  
    List<List<int>> dp = new List<List<int>>();
    for(int i = 0; i < n + 1; i++)
    {
      dp.Add(new List<int>());
      for(int j = 0; j < m + 1; j++)
      {
        dp[i].Add(-1);
      }
    }
    Console.WriteLine(minDis(str1, str2, n, m, dp));
  }
}
 
// This code is contributed by divyeshrabadiya07.

Javascript




<script>
 
function minDis(s1,s2,n,m,dp)
{
    // If any String is empty,
  // return the remaining characters of other String
  if(n == 0)  
    return m;
  if(m == 0)  
    return n;
               
  // To check if the recursive tree
  // for given n & m has already been executed
  if(dp[n][m] != -1)  
    return dp[n][m];
                  
  // If characters are equal, execute
  // recursive function for n-1, m-1
  if(s1[n - 1] == s2[m - 1])
  {         
    if(dp[n - 1][m - 1] == -1)
    {             
      return dp[n][m] = minDis(s1, s2, n - 1, m - 1, dp);         
    }      
    else
      return dp[n][m] = dp[n - 1][m - 1]; 
  }
    
  // If characters are nt equal, we need to
            
  // find the minimum cost out of all 3 operations.    
  else
  {         
    let m1, m2, m3;        // temp variables 
    if(dp[n-1][m] != -1)
    {  
      m1 = dp[n - 1][m];    
    }         
    else
    
      m1 = minDis(s1, s2, n - 1, m, dp);    
    }          
              
    if(dp[n][m - 1] != -1)
    {              
      m2 = dp[n][m - 1];          
    }          
    else
    {  
      m2 = minDis(s1, s2, n, m - 1, dp);    
    }                                 
     
    if(dp[n - 1][m - 1] != -1)
    {  
      m3 = dp[n - 1][m - 1];    
    
    else
    
      m3 = minDis(s1, s2, n - 1, m - 1, dp);     
    }   
    return dp[n][m] = 1 + Math.min(m1, Math.min(m2, m3));      
  }
}
 
// Driver program
 
let str1 = "voldemort";
let str2 = "dumbledore";
 
let n= str1.length, m = str2.length;  
let dp = new Array(n + 1);
for(let i = 0; i < n + 1; i++)
{
    dp[i]=new Array(m+1);
    for(let j=0;j<m+1;j++)
        dp[i][j]=-1;
}
 
document.write(minDis(str1, str2, n, m, dp));
 
// This code is contributed by avanitrachhadiya2155
 
</script>

Output

7

Time Complexity: O(m x n) 
Auxiliary Space: O( m *n)+O(m+n) , (m*n) extra array space and (m+n) recursive stack space.

Space Optimization :

Given two strings string1 and string2 and we have to perform operations on string1. Find minimum number of edits (operations) required to convert ‘string1 ’ into ‘string2’.  

we can do these three Operation:

  1. Insert a character at any position of the string.
  2. Remove any character from the string.
  3. Replace any character from the string with any other character.

Approach Contains :

  1. Let’s define the length of the two strings, as n, m.

 int n = s.size();
 int m = t.size();

       2. Create the vectors.

we are creating the two vectors as Previous, Current of m+1 size (string2 size).

vector<int>prev(m+1, 0), curr(m+1, 0);

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

     3. then follow the String Matching. In this string matching we converts like

                if(s[i-1] == t[j-1])
               {
                   curr[j] = prev[j-1];
               }
               else
               {
                   int mn = min(1 + prev[j], 1 + curr[j-1]);
                   curr[j] = min(mn, 1 + prev[j-1]);                   
               }

      //           if(s[i-1] == t[j-1])
     //          {
     //              dp[i][j] = dp[i-1][j-1];
     //          }
     //         else
     //          {
     //              int mn = min(1 + dp[i-1][j], 1 + dp[i][j-1]);
    //               dp[i][j] = min(mn, 1 + dp[i-1][j-1]);                   
    //           }

      4. remember we are pointing dp vector like

instead of dp[i-1][j] –> prev  // only

and

instead of dp[i][j-1] –> curr  // only

C




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int min(int a, int b, int c)
{
    if (a < b && a < c) {
        return a;
    }
    else if (b < a && b < c) {
        return b;
    }
    else {
        return c;
    }
}
 
int editDistance(char* s, char* t)
{
    int n = strlen(s);
    int m = strlen(t);
 
    int* prev = (int*)calloc(m + 1, sizeof(int));
    int* curr = (int*)calloc(m + 1, sizeof(int));
 
    for (int j = 0; j <= m; j++) {
        prev[j] = j;
    }
 
    for (int i = 1; i <= n; i++) {
        curr[0] = i;
        for (int j = 1; j <= m; j++) {
            if (s[i - 1] == t[j - 1]) {
                curr[j] = prev[j - 1];
            }
            else {
                int mn = min(1 + prev[j], 1 + curr[j - 1],
                             1 + prev[j - 1]);
                curr[j] = mn;
            }
        }
        memcpy(prev, curr, (m + 1) * sizeof(int));
    }
 
    int ans = prev[m];
    free(prev);
    free(curr);
 
    return ans;
}
 
int main()
{
    char s[] = "geek";
    char t[] = "gesek";
 
    int ans = editDistance(s, t);
    printf("%d\n", ans);
 
    return 0;
}

C++




// A Space efficient Dynamic Programming
// based C++ program to find minimum
// number operations to convert str1 to str2
#include <bits/stdc++.h>
using namespace std;
 
class Solution
{
      public:
     
    // space optimization
    int editDistance(string s, string t)
    {
        int n = s.size();
        int m = t.size();
         
        vector<int>prev(m+1, 0), curr(m+1, 0);
         
        for(int j =0; j<=m; j++)
        {
            prev[j] = j;
        }
         
        for(int i = 1; i <= n; i++)
        {
            curr[0] = i;
            for(int j = 1; j<= m; j++)
            {
                if(s[i-1] == t[j-1])
                {
                    curr[j] = prev[j-1];
                }
                else
                {
                    int mn = min(1 + prev[j], 1 + curr[j-1]);
                    curr[j] = min(mn, 1 + prev[j-1]);                  
                }
            }
            prev = curr;
        }
         
        return prev[m];
    }
     
};
 
int main()
{
    string s = "geek", t = "gesek";
 
    Solution ob;
    int ans = ob.editDistance(s, t);
    cout << ans << "\n";
 
    return 0;
}

Java




// A Space efficient Dynamic Programming
// based Java  program to find minimum
// number operations to convert str1 to str2
import java.util.*;
 
class Solution {
    // space optimization
    public int editDistance(String s, String t)
    {
        int n = s.length();
        int m = t.length();
 
        int[] prev = new int[m + 1];
        int[] curr = new int[m + 1];
 
        for (int j = 0; j <= m; j++) {
            prev[j] = j;
        }
 
        for (int i = 1; i <= n; i++) {
            curr[0] = i;
            for (int j = 1; j <= m; j++) {
                if (s.charAt(i - 1) == t.charAt(j - 1)) {
                    curr[j] = prev[j - 1];
                }
                else {
                    int mn = Math.min(1 + prev[j],
                                      1 + curr[j - 1]);
                    curr[j] = Math.min(mn, 1 + prev[j - 1]);
                }
            }
            prev = curr.clone();
        }
 
        return prev[m];
    }
}
 
public class Main {
    public static void main(String[] args)
    {
        String s = "geek";
        String t = "gesek";
 
        Solution ob = new Solution();
        int ans = ob.editDistance(s, t);
        System.out.println(ans);
    }
}

Python3




# A Space efficient Dynamic Programming
# based Python3 program to find minimum
# number operations to convert str1 to str2
class Solution:
    def editDistance(self, s: str, t: str) -> int:
        n = len(s)
        m = len(t)
 
        prev = [j for j in range(m+1)]
        curr = [0] * (m+1)
 
        for i in range(1, n+1):
            curr[0] = i
            for j in range(1, m+1):
                if s[i-1] == t[j-1]:
                    curr[j] = prev[j-1]
                else:
                    mn = min(1 + prev[j], 1 + curr[j-1])
                    curr[j] = min(mn, 1 + prev[j-1])
            prev = curr.copy()
 
        return prev[m]
 
s = "geek"
t = "gesek"
 
ob = Solution()
ans = ob.editDistance(s, t)
print(ans)

C#




using System;
using System.Collections.Generic;
 
class Solution {
    public int EditDistance(string s, string t)
    {
        int n = s.Length;
        int m = t.Length;
 
        List<int> prev = new List<int>();
        List<int> curr = new List<int>();
 
        for (int j = 0; j <= m; j++) {
            prev.Add(j);
        }
 
        for (int i = 1; i <= n; i++) {
            curr.Add(i);
            for (int j = 1; j <= m; j++) {
                if (s[i - 1] == t[j - 1]) {
                    curr.Add(prev[j - 1]);
                }
                else {
                    int mn = Math.Min(1 + prev[j],
                                      1 + curr[j - 1]);
                    curr.Add(Math.Min(mn, 1 + prev[j - 1]));
                }
            }
            prev = new List<int>(curr);
            curr.Clear();
        }
 
        return prev[m];
    }
}
 
class Program {
    static void Main(string[] args)
    {
        string s = "geek";
        string t = "gesek";
 
        Solution ob = new Solution();
        int ans = ob.EditDistance(s, t);
        Console.WriteLine(ans);
    }
}
 
// This code is contributed by sarojmcy2e

Javascript




class Solution {
  // space optimization
  editDistance(s, t) {
    const n = s.length;
    const m = t.length;
 
    const prev = new Array(m + 1).fill(0);
    const curr = new Array(m + 1).fill(0);
 
    for (let j = 0; j <= m; j++) {
      prev[j] = j;
    }
 
    for (let i = 1; i <= n; i++) {
      curr[0] = i;
      for (let j = 1; j <= m; j++) {
        if (s[i - 1] === t[j - 1]) {
          curr[j] = prev[j - 1];
        } else {
          const mn = Math.min(1 + prev[j], 1 + curr[j - 1]);
          curr[j] = Math.min(mn, 1 + prev[j - 1]);
        }
      }
      prev.splice(0, m + 1, ...curr);
    }
 
    return prev[m];
  }
}
 
const s = "geek";
const t = "gesek";
 
const ob = new Solution();
const ans = ob.editDistance(s, t);
console.log(ans);

Output:

1

Time Complexity: O(m x n).
Auxiliary Space: O( m x n), it don’t take the extra (m+n) recursive stack space.

Applications: There are many practical applications of edit distance algorithm, refer Lucene API for sample. Another example, display all the words in a dictionary that are near proximity to a given wordincorrectly spelled word.

Thanks to Vivek Kumar for suggesting updates.
Thanks to Venki for providing initial post. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
 


My Personal Notes arrow_drop_up
Last Updated : 26 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials