Minimize partitions in given string to get another string
Given two strings A and B, print the minimum number of slices required in A to get another string B. In case, if it is not possible to get B from A, then print “-1”.
Input: A = “geeksforgeeks”, B = “ksgek”
Explanation: g | ee | ks | forge | ek | s : minimum 5 slices are required to create B
Input: A = “topgames”, B = “mepo”
Explanation: t | o | p | ga | me | s : minimum 5 slices are required to create B
Input: A = “memk”, B = “memo”
Explanation: Not possible to create B with the help of A
Approach: This problem is a variation of the Longest Common Substring problem. The main idea to do this problem is to get the longest common substring between A and B and then decide on the basis of the start index of the common substring in A, the number of slices needed to cut that portion from A. Then take out that portion from A with either 1 or 2 slices. Also, remove that substring from B and replace that substring with “0” or anything other than alphabets in the case of A. Now, follow the below steps to solve this problem:
- First, make a simple check with lengths of A and B. If B is longer, then return -1.
- Now the first step is to find the longest common substring in both the strings.
- Now, if the start index or the end index of that common substring in String A is 0 or N (A.length()-1) respectively, then in that only 1 slice is needed to cut that portion out.
For example: A = “game” and B = “ga” then ga | me. Only one slice is required
- If the substring is between the first and last character of string A, then in that case, 2 slices are required to cut that portion out.
For example: A = “gamer” and B = “me” -> ga | me | r . Two slices are required
- Now, reduce the size of B by removing the current longest substring from it. It is necessary to do this because so that a different substring is chosen as the longest common substring in the next call longestSubstring().
- After that, replace that common substring present in A with the character “0”. The substring can not be removed directly from A because the order is important as we are using the index of common substring present in A to decide the number of slices.
- Repeat the same process until the string B becomes empty.
Below is the implementation of the above approach:
Time complexity: O(N*(M2)) where N is the length of string A and M is the length of string B
Auxiliary space: O(M)