VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-all-interleavings-of-given-two-strings/

⇱ Print all interleavings of given two strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print all interleavings of given two strings

Last Updated : 16 Aug, 2024

Given two strings str1 and str2, write a function that prints all interleavings of the given two strings. You may assume that all characters in both strings are different 

Example: 

Input: str1 = "AB", str2 = "CD"
Output:
ABCD
ACBD
ACDB
CABD
CADB
CDAB

Input: str1 = "AB", str2 = "C"
Output:
ABC
ACB
CAB

An interleaved string of given two strings preserves the order of characters in individual strings. For example, in all the interleavings of above first example, 'A' comes before 'B' and 'C' comes before 'D'.

Let the length of str1 be m and the length of str2 be n. Let us assume that all characters in str1 and str2 are different. Let count(m, n) be the count of all interleaved strings in such strings. The value of count(m, n) can be written as following. 

count(m, n) = count(m-1, n) + count(m, n-1)
count(1, 0) = 1 and count(0, 1) = 1

To print all interleavings, we can first fix the first character of str1[0..m-1] in output string, and recursively call for str1[1..m-1] and str2[0..n-1]. And then we can fix the first character of str2[0..n-1] and recursively call for str1[0..m-1] and str2[1..n-1]. Thanks to akash01 for providing following C implementation. 


Output
ABCD
ACBD
ACDB
CABD
CADB
CDAB

Time Complexity: O(2 ^ (m+n))
Auxiliary Space: O(1)

Approach 2: Using Buttom-Up Approach /Tabulation Method of Dynamic Programming


Output
CDAB
CADB
ACDB
CABD
ACBD
ABCD

Time complexity: O(m * n * L), where m and n are the lengths of str1 and str2 respectively, and L is the average length of the interleaved strings.
Auxiliary Space: O(m * n * L), where m and n are the lengths of str1 and str2 respectively, and L is the average length of the interleaved strings.

Comment
Article Tags:
Article Tags: