Given two strings S1 and S2, the task is to check if it’s possible to generate string S2 by repeatedly appending subsequences of S1 to the end of an initially empty string. If possible, print “YES” and the minimum number of operations required. Otherwise, print “NO“.
Input: S1 = “acebcd”, S2 = “acbcd”
Explanation: Append subsequence “acbc” followed by “d” to obtain S2.
Input: S1 = “aceasd”, S2 = “asdxds”
Explanation: Since character ‘x’ is not present in S1, S2 cannot be obtained.
Approach: Follow the steps below to solve the problem:
- Iterate over characters of string S1 and store frequencies of each character in S1 in an array freq.
- Traverse the string S2 and check if there is any character in S2 which is not present in S1. If any such character is found, print “NO”.
- Otherwise, iterate over characters in S1 and update indices of each character in a Set
- Traverse string S2 and for each character, check if it can be included in the current subsequence of S1 that can be appended.
- If found to be true, set the index of current character as that of the last character appended. Otherwise, increase count of subsequences and set the index of current character as that of the last character appended. Proceed to the next character.
- finally, print “YES” and the count of such subsequences as the required answer.
Below is the implementation of the above approach:
Time Complexity: O(Mlog(N))
Auxiliary Space: O(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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes