Interleaving String - Problem

Given strings s1, s2, and s3, determine whether s3 is formed by an interleaving of s1 and s2.

An interleaving of two strings s and t is a configuration where s and t are divided into substrings such that:

  • s = s1 + s2 + ... + sn
  • t = t1 + t2 + ... + tm
  • |n - m| ≤ 1

The interleaving is s1 + t1 + s2 + t2 + s3 + t3 + ... or t1 + s1 + t2 + s2 + t3 + s3 + ...

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

Input & Output

Example 1 — Valid Interleaving
$ Input: s1 = "aab", s2 = "axy", s3 = "aaxaby"
Output: true
💡 Note: We can form s3 by taking: a(s1) + a(s2) + a(s1) + x(s2) + b(s1) + y(s2) = "aaxaby"
Example 2 — Invalid Interleaving
$ Input: s1 = "aab", s2 = "axy", s3 = "aabcxy"
Output: false
💡 Note: Character 'c' appears in s3 but not in s1 or s2, so interleaving is impossible
Example 3 — Empty String Cases
$ Input: s1 = "", s2 = "", s3 = ""
Output: true
💡 Note: Empty strings can form an empty string by interleaving

Constraints

  • 0 ≤ s1.length, s2.length ≤ 100
  • 0 ≤ s3.length ≤ 200
  • s1, s2, and s3 consist of lowercase English letters

Visualization

Tap to expand
Interleaving String: Can s1 and s2 form s3?s1 = "aab"a a bs2 = "axy"a x ys3 = "aaxaby"a a x a b yInterleaving Process:as1[0]as2[0]xs2[1]as1[1]bs1[2]ys2[2]Result: "aaxaby" = s3 ✓Interleaving Valid!Characters from s1 and s2 maintain their relative order
Understanding the Visualization
1
Input Strings
Two source strings s1, s2 and target string s3
2
Interleaving Process
Alternate taking characters from s1 and s2 while preserving order
3
Validation
Check if the interleaved result matches s3 exactly
Key Takeaway
🎯 Key Insight: At each position in s3, we know exactly how many characters we've used from s1 and s2, making DP possible
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
180.0K Views
Medium Frequency
~25 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen