Given three strings A, B and C. Write a function that checks whether C is an interleaving of A and B. C is said to be interleaving A and B, if it contains all characters of A and B and order of all characters in individual strings is preserved.
We have discussed a simple solution of this problem here. The simple solution doesn’t work if strings A and B have some common characters. For example A = “XXY”, string B = “XXZ” and string C = “XXZXXXY”. To handle all cases, two possibilities need to be considered.
a) If first character of C matches with first character of A, we move one character ahead in A and C and recursively check.
b) If first character of C matches with first character of B, we move one character ahead in B and C and recursively check.
If any of the above two cases is true, we return true, else false. Following is simple recursive implementation of this approach (Thanks to Frederic for suggesting this)
The worst case time complexity of recursive solution is O(2n). The above recursive solution certainly has many overlapping subproblems. For example, if wee consider A = “XXX”, B = “XXX” and C = “XXXXXX” and draw recursion tree, there will be many overlapping subproblems.
Therefore, like other typical Dynamic Programming problems, we can solve it by creating a table and store results of subproblems in bottom up manner. Thanks to Abhinav Ramana for suggesting this method and implementation.
XXZXXXY is not interleaved of XXY and XXZ WZXY is interleaved of XY and WZ XXY is interleaved of XY and X XXY is not interleaved of YX and X XXXXZY is interleaved of XXY and XXZ
See this for more test cases.
Time Complexity: O(MN)
Auxiliary Space: O(MN)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Given a string and an integer k, find the kth sub-string when all the sub-strings are sorted according to the given condition
- Find all palindromic sub-strings of a given string | Set 2
- Given two strings, find if first string is a subsequence of second
- Find all distinct palindromic sub-strings of a given string
- Find a string in lexicographic order which is in between given two strings
- Find the longest string that can be made up of other strings from the array
- Find the number of strings formed using distinct characters of a given string
- Meta Strings (Check if two strings can become same after a swap in one string)
- Number of sub-strings which are anagram of any sub-string of another string
- Sub-strings of a string that are prefix of the same string
- Frequency of a string in an array of strings
- String from prefix and suffix of given two strings
- Count All Palindrome Sub-Strings in a String | Set 2
- String matching with * (that matches with any) in any of the two strings
- Count All Palindrome Sub-Strings in a String | Set 1