VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-whether-a-given-string-is-an-interleaving-of-two-other-given-strings/

⇱ Interleaving of two given strings with no common characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Interleaving of two given strings with no common characters

Last Updated : 23 Jul, 2025

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 strings

Input: 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,

  • Since both the input strings have mutually exclusive characters, a character of s3 will either match with a character of s1 or s2.
  • We traverse through s3 and compare its every character with next character in s1 or next in s2. If any one matches, we move ahead in that string. If none of the two match, we return false.
  • We return true if we traversed all characters of s3 and every character matched either s1 or s2

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

Comment
Article Tags:
Article Tags: