Given two strings ‘str1’ and ‘str2’ of size m and n respectively. The task is to remove/delete and insert minimum number of characters from/in str1 so as to transform it into str2. It could be possible that the same character needs to be removed/deleted from one point of str1 and inserted to some another point.
Input : str1 = "heap", str2 = "pea" Output : Minimum Deletion = 2 and Minimum Insertion = 1 p and h deleted from heap Then, p is inserted at the beginning One thing to note, though p was required yet it was removed/deleted first from its position and then it is inserted to some other position. Thus, p contributes one to the deletion_count and one to the insertion_count. Input : str1 = "geeksforgeeks", str2 = "geeks" Output : Minimum Deletion = 8 Minimum Insertion = 0
A simple solution is to consider all subsequences of str1 and for each subsequence calculate minimum deletions and insertions so as to transform it into str2. A very complex method and the time complexity of this solution is exponential.
An efficient approach uses the concept of finding the length of the longest common subsequence of the given two sequences.
-->str1 and str2 be the given strings. -->m and n be their lengths respectively. -->len be the length of the longest common subsequence of str1 and str2 -->// minimum number of deletions minDel = m - len -->// minimum number of Insertions minInsert = n - len
Minimum number of deletions = 2 Minimum number of insertions = 1
Time Complexity: O(m * n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Convert to Strictly increasing array with minimum changes
- Ways of transforming one string to other by removing 0 or more characters
- Count the number of ways to tile the floor of size n x m using 1 x m size tiles
- Minimum insertions to sort an array
- Shortest Uncommon Subsequence
- Count number of ways to jump to reach end
- Minimum number of deletions to make a sorted sequence
- Minimum steps to delete a string after repeated deletion of palindrome substrings
- Minimum number of deletions to make a string palindrome
- Minimum Cost To Make Two Strings Identical
- Find minimum adjustment cost of an array
- Bitmasking and Dynamic Programming | Set 1 (Count ways to assign unique cap to every person)
- Minimum insertions to form a palindrome | DP-28
- Edit Distance | DP-5
- Longest Common Subsequence | DP-4
Improved By : nitin mittal