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
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.
ABCD ACBD ACDB CABD CADB CDAB
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print all the duplicates in the input string
- A Program to check if strings are rotations of each other or not
- Print reverse of a string using recursion
- Write a program to print all permutations of a given string
- Print list items containing all characters of a given word
- Check whether two strings are anagram of each other
- Print all permutations with repetition of characters
- Interleaving of two given strings with no common characters
- Print all permutations in sorted (lexicographic) order
- Given a sequence of words, print all anagrams together | Set 1
- Given a sequence of words, print all anagrams together | Set 2
- Find if a string is interleaved of two other strings | DP-33
- Print all ways to break a string in bracket form
- Print all possible words from phone digits
- Find if an array of strings can be chained to form a circle | Set 1
Improved By : rathbhupendra