VOOZH about

URL: https://www.geeksforgeeks.org/dsa/edit-distance-and-lcs-longest-common-subsequence/

⇱ Edit distance and LCS (Longest Common Subsequence) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Edit distance and LCS (Longest Common Subsequence)

Last Updated : 11 Jul, 2025

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:


Output
2

Complexity Analysis:

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