Given three strings, return true if the third string is interleaving the first and second strings, i.e., it is formed from all characters of the first and second string, and the order of characters is preserved.

For example,

ACDB is interleaving of AB and CD
 
ADEBCF is interleaving of ABC and DEF
 
ACBCD is interleaving of ABC and CD
 
ACDABC is interleaving of ABC and ACD

Practice this problem

We can easily solve this problem by using recursion, as demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

Interleaving

Java


Download  Run Code

Output:

Interleaving

Python


Download  Run Code

Output:

Interleaving

The time complexity of the above solution is O(m + n), where m and n are the length of the string X and Y. The auxiliary space required by the program is O(1).

 
The problem with the above solution is that it doesn’t handle duplicates. Suppose X = "ABC" and Y = "ACD", then the above solution will return false for string S = "ACDABC". The reason is that if the current character of S matches the current character of both X and Y, the solution will always pair S with X and do not check if the solution can be formed by pairing S with Y or not.

We can easily handle duplicates by pairing S with both X and Y and recursively check if the solution can be formed by either of them or not. Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

Interleaving

Java


Download  Run Code

Output:

Python


Download  Run Code

Output:

Interleaving

The worst-case time complexity of the above solution is exponential and occupies space in the call stack. The worst case happens when all characters of X and Y are the same. We can use dynamic programming to reduce the worst-case time complexity and space complexity to O(m.n).

The DP solution is discussed below in C++, Java, and Python:

C++


Download  Run Code

Output:

Interleaving

Java


Download  Run Code

Output:

Interleaving

Python


Download  Run Code

Output:

Interleaving

We can even write a bottom-up version of the above memoized solution. The following code shows how to implement it in C++, Java, and Python:

C++


Download  Run Code

Output:

Interleaving

Java


Download  Run Code

Output:

Interleaving

Python


Download  Run Code

Output:

Interleaving