Given two strings str1 and str2 of lengths N and M respectively, the task is to check if str2 can be formed by appending subsequences of str1 multiple times. If possible, print the minimum number of append operations required. Otherwise, print -1.
Input: str1 = “abb”, str2 = “ababbbbb”
String str2 can be formed by appending subsequences of str1 = “ab” + “abb” + “bb” + “b” = “ababbbbb”. Since at least 4 operations are required, print 4.
Input: str1 = “mt”, str2 = “atttm”
Since ‘a’ is not present in the string str1, str2 cannot be generated from str1. Therefore, print -1.
Approach: The idea is to use the concept of Hashing based on the following observations below:
- Consider strings str1 = “abb” and str2 = “aba”. Find the position of character str2 in str1 whose index is greater than or equals to 0 i.e., index 0 of str1.
- Again, find str2 in str1 such that its index is greater than or equals to 1 i.e., index 1 of str1.
- Then, find str2 in str1 such that its index is greater than or equals to 2 which does not exist.
- Therefore, start again from index 0 and find str2 in str1 having an index greater than or equals to index 0 i.e., index 0 of str1.
- Hence, two subsequences “ab” and “a” can be appended to form “aba”.
Follow the below steps to solve the problem:
- Initialize an array of vectors vec of length 26.
- Push all the indices str1 having character ‘a’ in vec. Similarly, push all indices having character ‘b’ in vec. Do this for every character from ‘a’ to ‘z’.
- Initialize a variable result with 1 and position with 0 to store the minimum operations and current position of str1.
- Traverse the string str2 over the range [0, M] and for each character do the following:
- If vec[str2[i] – ‘a’] is empty then the character str2[i] is not present in str1. Hence, the answer is not possible. Therefore, print -1.
- Otherwise, find the lower bound of position in vec[str2[i] – ‘a’]. Let it be p. If p is equals the size of the vec[str2[i] – ‘a’] then increment the result by 1 and decrement i by 1 as answer for character str2[i] is not found yet and set position to 0.
- Otherwise, set position as (vec[p] + 1).
- After traversing, print the result as the minimum operations required.
Below is the implementation of the above approach:
Time Complexity: O(N + M log N)
Auxiliary Space: O(M + N)
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.