Statement

Given strings s1, s2, and s3, find whether an interleaving of s1 and s2 forms s3.

An interleaving of two strings a and b is a configuration where a and b splits into nn and mm substrings, respectively, such that:

  • a =a1= a_{1} + a2a_{2} + … + ana_{n}
  • b =b1= b_{1} + b2b_{2} + … + bmb_{m}
  • nm1\left | n - m \right | \leqslant 1
  • The interleaving can follow either of the following two formats:
    • a1+b1+a2+b2+a3+b3+...a_{1} + b_{1} + a_{2} + b_{2} + a_{3} + b_{3} + ...
    • b1+a1+b2+a2+b3+a3+...b_{1} + a_{1} + b_{2} + a_{2} + b_{3} + a_{3} + ...
  • axa_{x} can be a consecutive sequence of characters in string s1.
  • bxb_{x} can be a consecutive sequence of characters in string s2.

Note: a+ba + b is the concatenation of the strings aa and bb.

Let’s say we have two strings, “abc” and “xyz”. We may interleave them in multiple ways. We may alternately pick one character from each string until we have used up all the characters, giving us “axbycz” and “xaybzc”. Or, we may try to pick two characters at a time from each string, giving us “abxycz” and “xyabzc”. If we pick three characters at a time, we get “abcxyz” and “xyzabc”. Another class of variations is to pick a variable number of characters from each string, which leads to many more possibilities, such as “abxcyz”, “xayzbc”, and so on. However, “bxaycz” is not a valid interleaving, as the order of the characters taken from the first string is not preserved, since “b” appears here before “a”. Similarly, “acxybz” is not a valid interleaving.

Constraints:

  • 00 \leq s1.length, s2.length 375\leq 375
  • 00 \leq s3.length 750\leq 750
  • s1, s2, and s3 consist of lowercase English letters.

Examples

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.