![]() |
VOOZH | about |
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".
Examples :
Input: A = "geeksforgeeks", B = "ksgek"
Output: 5
Explanation: g | ee | ks | forge | ek | s : minimum 5 slices are required to create BInput: A = "topgames", B = "mepo"
Output: 5
Explanation: t | o | p | ga | me | s : minimum 5 slices are required to create BInput: A = "memk", B = "memo"
Output: -1
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:
For example: A = "game" and B = "ga" then ga | me. Only one slice is required
For example: A = "gamer" and B = "me" -> ga | me | r . Two slices are required
Below is the implementation of the above approach:
5
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)