![]() |
VOOZH | about |
Given three strings s1, s2 and s3. check whether s3 is an interleaving of s1 and s2. It may be assumed that there is no common character between s1 and s2 A string s3 is said to be interleaving s1 and s2, if it contains all characters of s1 and s2 and order of all characters in individual strings is preserved.
Input: s1 = "AB", s2 = "C", s3 = "ACB",
Output: true
s3 has all characters of s1 and s2 and retains order of characters in both the stringsInput: s1 = "AXY", s2 = "BBZ", s3 = "BBAZXY",
Output: true
The string BBAZXY has all characters of the other two strings and in the same order.
Input: s1 = "AB", s2 = "CD", s3 = "ACBG",
Output: false
D is missing in s3
Please see this for an extended solution that handles common characters also,
Time Complexity: O(m+n) where m and n are the lengths of strings s1 and s2 respectively.
Auxiliary Space : O(1)
Note that the above approach doesn't work if s1 and s2 have some characters in common. For example, if string s1 = "AAB", string s2 = "AAC" and string s3 = "AACAAB", then the above method will return false. We have discussed here an extended solution that handles common characters.