Minimize removal or insertions required to make two strings equal
- Remove a character from either end.
- Insert a character at any position.
Print the count of the minimum number of operations required.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: S = “qpmon”, T = “mnopq”
Operation 1: Remove ‘n’ from the end, and insert it at the second last position. The string S modifies to “qpmno”.
Operation 2: Remove ‘q’ from the start, and insert it at the last position. The string S modifies to “pmnoq”.
Operation 3: Remove ‘p’ from the start, and insert it at the second last position. The string S modifies to “mnopq” which is same as the desired string T.
Input: S = “abab”, T = “baba”
Approach: The given problem can be solved by the following observation:
- It is required to find the length of the longest substring of A which is a subsequence in B. Let the length of that sub string be L.
- Then, the remaining characters can be inserted without disturbing the existing order.
- To conclude, the optimal answer will be equal to N – L.
Therefore, from the above observations, the minimum number of operations required is the difference between N and the length of the longest substring of the string A which is a subsequence in the string B.
Below is the implementation of the above approach:
Time Complexity: O(N2 )
Space Complexity: O(N2)