Distinct strings such that they contains given strings as sub-sequences
Given two strings str1 and str2 of lengths M and N respectively. The task is to find all the distinct string of length M + N such that the frequency of any character in the resultant string is equal to the sum of frequencies of the same character in the given strings and both the given strings are present as a sub-sequence in all the generated strings.
Input: str = “aa”, str2 = “ab”
Input: str1 = “ab”, str2 = “de”
Approach: This problem can be solved using recursion. Set two pointers i and j to the beginnings of strings str1 and str2 respectively. Now, at every recursive call we have two choices to select either the character at str1[i] or the character at str2[j] and the termination condition will be when the length of the resultant string becomes equal to len(str1) + len(str2). Use an unordered_set in order to avoid duplicates.
Below is the implementation of the above approach:
aaab aaba abaa
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.