Find all interleavings of given strings that can be formed from all the characters of the first and second string where the order of characters is preserved.

For example, interleavings of string ABC and ACB are:

ACBABC, AABCBC, ACABCB, ABCACB, AACBBC, ABACCB, ACABBC, ABACBC, AACBCB, AABCCB

Practice this problem

We can easily solve this problem by using recursion. The idea is to append the first or last character of X and Y in the result one by one, and recur for the remaining substring.

Input: X[1…m], Y[1…n]
 
fun(X, m, Y, n) = fun(X, m-1, Y, n) + X[m]
                  fun(X, m, Y, n-1) + Y[n]
 
fun(X, 0, Y, n) = Y[n]    // X is empty
fun(X, m, Y, 0) = X[m]    // Y is empty

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

ACBABC
AABCBC
ACABCB
ABCACB
AACBBC
ABACCB
ACABBC
ABACBC
AACBCB
AABCCB

Java


Download  Run Code

Output:

[AACBCB, ABCACB, ACBABC, ABACCB, ACABCB, AABCCB, ACABBC, AACBBC, ABACBC, AABCBC]

Python


Download  Run Code

Output:

{‘ABACBC’, ‘ABACCB’, ‘ACBABC’, ‘AACBBC’, ‘ACABCB’, ‘AABCCB’, ‘AACBCB’, ‘AABCBC’, ‘ABCACB’, ‘ACABBC’}

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).