Minimum Deletions & Insertions To Transform a String into another
Last updated
Was this helpful?
Last updated
Was this helpful?
Given strings s1 and s2, we need to transform s1 into s2 by deleting and inserting characters. Write a function to calculate the count of the minimum number of deletion and insertion operations.
Example 1:
Example 2:
This problem can easily be converted to the Longest Common Subsequence (LCS). If we can find the LCS of the two input strings, we can easily find how many characters we need to insert and delete from s1. Here is how we can do this:
Let’s assume len1 is the length of s1 and len2 is the length of s2.
Now let’s assume c1 is the length of LCS of the two strings s1 and s2.
To transform s1 into s2, we need to delete everything from s1 which is not part of LCS, so minimum deletions we need to perform from s1 => len1 - c1
Similarly, we need to insert everything in s1 which is present in s2 but not part of LCS, so minimum insertions we need to perform in s1 => len2 - c1
The time and space complexity for this is O(m*n), where ‘m’ and ‘n’ are the lengths of the two input strings.