VOOZH about

URL: https://www.geeksforgeeks.org/dsa/distinct-strings-such-that-they-contains-given-strings-as-sub-sequences/

⇱ Distinct strings such that they contains given strings as sub-sequences - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Distinct strings such that they contains given strings as sub-sequences

Last Updated : 12 Jul, 2025

Given two strings str1 and str2 of lengths M and N respectively. The task is to find all the distinct strings 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.

Examples: 

Input: str = "aa", str2 = "ab" 
Output: 
abaa 
aaab 
aaba
Input: str1 = "ab", str2 = "de" 
Output: 
deab 
daeb 
adeb 
abde 
dabe 
adbe 

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: 


Output
aaab
aaba
abaa

Time complexity: O()
Auxiliary Space: O(length(str1)+length(str2))

Comment