The Wayback Machine - https://web.archive.org/web/20240711022847/https://www.geeksforgeeks.org/edit-distance-and-lcs-longest-common-subsequence/
Open In App

Edit distance and LCS (Longest Common Subsequence)

Last Updated : 29 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In standard Edit Distance where we are allowed 3 operations, insert, delete, and replace. Consider a variation of edit distance where we are allowed only two operations insert and delete, find edit distance in this variation. 

Examples:  

Input : str1 = "cat", st2 = "cut"
Output : 2
We are allowed to insert and delete. We delete 'a'
from "cat" and insert "u" to make it "cut".

Input : str1 = "acb", st2 = "ab"
Output : 1
We can convert "acb" to "ab" by removing 'c'. 

One solution is to simply modify the Edit Distance Solution by making two recursive calls instead of three. An interesting solution is based on LCS. 

  1. Find LCS of two strings. Let the length of LCS be x. 
  2. Let the length of the first string be m and the length of the second string be n. Our result is (m – x) + (n – x). We basically need to do (m – x) delete operations and (n – x) insert operations.  

Implementation:

C++




// CPP program to find Edit Distance (when only two
// operations are allowed, insert and delete) using LCS.
#include<bits/stdc++.h>
using namespace std;
 
int editDistanceWith2Ops(string &X;, string &Y;)
{
    // Find LCS
    int m = X.length(), n = Y.length();
    int L[m+1][n+1];
    for (int i=0; i<=m; i++)
    {
        for (int j=0; j<=n; j++)
        {
            if (i == 0 || j == 0)
                L[i][j] = 0;
            else if (X[i-1] == Y[j-1])
                L[i][j] = L[i-1][j-1] + 1;
            else
                L[i][j] = max(L[i-1][j], L[i][j-1]);
        }
    }   
    int lcs  = L[m][n];
 
    // Edit distance is delete operations +
    // insert operations.
    return (m - lcs) + (n - lcs);
}
 
/* Driver program to test above function */
int main()
{
    string X = "abc", Y = "acd";
    cout << editDistanceWith2Ops(X, Y);
    return 0;
}


Java




//Java program to find Edit Distance (when only two
// operations are allowed, insert and delete) using LCS.
 
class GFG {
 
    static int editDistanceWith2Ops(String X, String Y) {
        // Find LCS
        int m = X.length(), n = Y.length();
        int L[][] = new int[m + 1][n + 1];
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0 || j == 0) {
                    L[i][j] = 0;
                } else if (X.charAt(i - 1) == Y.charAt(j - 1)) {
                    L[i][j] = L[i - 1][j - 1] + 1;
                } else {
                    L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
                }
            }
        }
        int lcs = L[m][n];
 
        // Edit distance is delete operations +
        // insert operations.
        return (m - lcs) + (n - lcs);
    }
 
    /* Driver program to test above function */
    public static void main(String[] args) {
        String X = "abc", Y = "acd";
        System.out.println(editDistanceWith2Ops(X, Y));
 
    }
}
/* This Java code is contributed by 29AjayKumar*/


Python 3




# Python 3 program to find Edit Distance
# (when only two operations are allowed,
# insert and delete) using LCS.
 
def editDistanceWith2Ops(X, Y):
 
    # Find LCS
    m = len(X)
    n = len(Y)
    L = [[0 for x in range(n + 1)]
            for y in range(m + 1)]
    for i in range(m + 1):
        for j in range(n + 1):
            if (i == 0 or j == 0):
                L[i][j] = 0
            elif (X[i - 1] == Y[j - 1]):
                L[i][j] = L[i - 1][j - 1] + 1
            else:
                L[i][j] = max(L[i - 1][j],
                              L[i][j - 1])
 
    lcs = L[m][n]
 
    # Edit distance is delete operations +
    # insert operations.
    return (m - lcs) + (n - lcs)
 
# Driver Code
if __name__ == "__main__":
     
    X = "abc"
    Y = "acd"
    print(editDistanceWith2Ops(X, Y))
 
# This code is contributed by ita_c


C#




// C# program to find Edit Distance
// (when only two operations are
// allowed, insert and delete) using LCS.
using System;
 
class GFG
{
 
static int editDistanceWith2Ops(String X,
                                String Y)
{
    // Find LCS
    int m = X.Length, n = Y.Length;
    int [ , ]L = new int[m + 1 , n + 1];
    for (int i = 0; i <= m; i++)
    {
        for (int j = 0; j <= n; j++)
        {
            if (i == 0 || j == 0)
            {
                L[i , j] = 0;
            }
            else if (X[i - 1] == Y[j - 1])
            {
                L[i , j] = L[i - 1 , j - 1] + 1;
            }
            else
            {
                L[i , j] = Math.Max(L[i - 1 , j],
                                    L[i , j - 1]);
            }
        }
    }
    int lcs = L[m , n];
 
    // Edit distance is delete operations +
    // insert operations.
    return (m - lcs) + (n - lcs);
}
 
// Driver Code
public static void Main()
{
    String X = "abc", Y = "acd";
    Console.Write(editDistanceWith2Ops(X, Y));
}
}
 
// This code is contributed
// by 29AjayKumar


PHP




<?php
// PHP program to find Edit Distance
// (when only two operations are allowed,
// insert and delete) using LCS.
 
function editDistanceWith2Ops($X, $Y)
{
    // Find LCS
    $m = strlen($X); $n = strlen($Y);
    $L[$m + 1][$n + 1];
    for ($i = 0; $i <= $m; $i++)
    {
        for ($j = 0; $j <= $n; $j++)
        {
            if ($i == 0 || $j == 0)
                $L[$i][$j] = 0;
            else if ($X[$i - 1] == $Y[$j - 1])
                $L[$i][$j] = $L[$i - 1][$j - 1] + 1;
            else
                $L[$i][$j] = max($L[$i - 1][$j],
                                 $L[$i][$j - 1]);
        }
    }
    $lcs = $L[$m][$n];
 
    // Edit distance is delete operations +
    // insert operations.
    return ($m - $lcs) + ($n - $lcs);
}
 
// Driver Code
$X = "abc"; $Y = "acd";
echo editDistanceWith2Ops($X, $Y);
 
// This code is contributed
// by Akanksha Rai
?>


Javascript




<script>
//Javascript program to find Edit Distance (when only two
// operations are allowed, insert and delete) using LCS.
     
    function editDistanceWith2Ops(X,Y)
    {
        // Find LCS
        let m = X.length, n = Y.length;
        let L = new Array(m + 1);
        for(let i=0;i<L.length;i++)
        {
            L[i]=new Array(n+1);
            for(let j=0;j<L[i].length;j++)
            {
                L[i][j]=0;
            }
        }
        for (let i = 0; i <= m; i++) {
            for (let j = 0; j <= n; j++) {
                if (i == 0 || j == 0) {
                    L[i][j] = 0;
                } else if (X[i-1] == Y[j-1]) {
                    L[i][j] = L[i - 1][j - 1] + 1;
                } else {
                    L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
                }
            }
        }
        let lcs = L[m][n];
  
        // Edit distance is delete operations +
        // insert operations.
        return (m - lcs) + (n - lcs);
    }
     
    /* Driver program to test above function */
    let X = "abc", Y = "acd";
    document.write(editDistanceWith2Ops(X, Y));
 
 
// This code is contributed by rag2127
</script>


Output

2

Complexity Analysis:

  • Time Complexity: O(m * n) 
  • Auxiliary Space: O(m * n)


Previous Article
Next Article

Similar Reads

Longest Common Subsequence (LCS) by repeatedly swapping characters of a string with characters of another string
Given two strings A and B of lengths N and M respectively, the task is to find the length of the longest common subsequence that can be two strings if any character from string A can be swapped with any other character from B any number of times. Examples: Input: A = "abdeff", B = "abbet"Output: 4Explanation: Swapping A[5] and B[4] modifies A to "a
7 min read
Find the Longest Common Subsequence (LCS) in given K permutations
Given K permutations of numbers from 1 to N in a 2D array arr[][]. The task is to find the longest common subsequence of these K permutations. Examples: Input: N = 4, K = 3arr[][] = {{1, 4, 2, 3}, {4, 1, 2, 3}, {1, 2, 4, 3}}Output: 3Explanation: Longest common subsequence is {1, 2, 3} which has length 3. Input: N = 6, K = 3,arr[][] = {{2, 5, 1, 4,
10 min read
Longest Common Increasing Subsequence (LCS + LIS)
Prerequisites : LCS, LIS Given two arrays, find length of the longest common increasing subsequence [LCIS] and print one of such sequences (multiple sequences may exist)Suppose we consider two arrays - arr1[] = {3, 4, 9, 1} and arr2[] = {5, 3, 8, 9, 10, 2, 1}Our answer would be {3, 9} as this is the longest common subsequence which is increasing al
15+ min read
LCS (Longest Common Subsequence) of three strings
Given 3 strings of all having length &lt; 100,the task is to find the longest common sub-sequence in all three given sequences. Examples: Input : str1 = "geeks" str2 = "geeksfor" str3 = "geeksforgeeks" Output : 5 Longest common subsequence is "geeks" i.e., length = 5 Input : str1 = "abcd1e2" str2 = "bc12ea" str3 = "bd1ea" Output : 3 Longest common
13 min read
Longest Common Subsequence (LCS)
Given two strings, S1 and S2, the task is to find the length of the Longest Common Subsequence, i.e. longest subsequence present in both of the strings.  A longest common subsequence (LCS) is defined as the longest subsequence which is common in all given input sequences. Examples: Input: S1 = "ABC", S2 = "ACD"Output: 2Explanation: The longest subs
15+ min read
Longest Increasing Subsequence using Longest Common Subsequence Algorithm
Given an array arr[] of N integers, the task is to find and print the Longest Increasing Subsequence.Examples: Input: arr[] = {12, 34, 1, 5, 40, 80} Output: 4 {12, 34, 40, 80} and {1, 5, 40, 80} are the longest increasing subsequences.Input: arr[] = {10, 22, 9, 33, 21, 50, 41, 60, 80} Output: 6 Prerequisite: LCS, LISApproach: The longest increasing
12 min read
Edit Distance | DP using Memoization
Given two strings str1 and str2 and below operations that can be performed on str1. Find the minimum number of edits (operations) required to convert 'str1' into 'str2'. InsertRemoveReplace All of the above operations are of equal cost. Examples: Input: str1 = "geek", str2 = "gesek" Output: 1 We can convert str1 into str2 by inserting a 's'. Input:
15+ min read
Check if edit distance between two strings is one
An edit between two strings is one of the following changes. Add a characterDelete a characterChange a characterGiven two string s1 and s2, find if s1 can be converted to s2 with exactly one edit. Expected time complexity is O(m+n) where m and n are lengths of two strings. Examples: Input: s1 = "geeks", s2 = "geek" Output: yes Number of edits is 1
15 min read
CSES Solutions - Edit Distance
The edit distance between two strings S1 and S2 is the minimum number of operations required to transform one string into the other. The allowed operations are: Add one character to the string.Remove one character from the string.Replace one character in the string.Your task is to calculate the edit distance between two strings. Examples: Input: S1
8 min read
Edit Distance
Given two strings str1 and str2 of length M and N respectively and below operations that can be performed on str1. Find the minimum number of edits (operations) to convert 'str1' into 'str2'.   Operation 1 (INSERT): Insert any character before or after any index of str1Operation 2 (REMOVE): Remove a character of str1Operation 3 (Replace): Replace a
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg