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.
- Minimum number of deletions to make a string palindrome | Set 2
- Minimum number of deletions to make a string palindrome
- Minimum number of deletions to make a sorted sequence
- Minimum insertions to sort an array
- Minimum insertions to form a palindrome | DP-28
- Check if it is possible to transform one string to another
- Minimum number of sub-strings of a string such that all are power of 5
- Minimum number of operations required to sum to binary string S
- Find number of times a string occurs as a subsequence in given string
- Minimum splits in a binary string such that every substring is a power of 4 or 6.
- Minimum cost to make a string free of a subsequence
- Minimum number of squares whose sum equals to given number n
- Minimum number of cubes whose sum equals to given number N
- Minimum replacements to make adjacent characters unequal in a ternary string | Set-2
- Minimum steps to delete a string by deleting substring comprising of same characters