Interleaving String - Problem
Given three strings s1, s2, and s3, determine whether s3 can be formed by interleaving the characters of s1 and s2.

An interleaving means we can split s1 and s2 into substrings and combine them while preserving the relative order of characters within each original string. Think of it like merging two sequences where you can pick from either sequence at each step, but you must maintain the order within each sequence.

For example, if s1 = "abc" and s2 = "def", then valid interleavings include: "adbecf", "defabc", "adbefc", etc.

Goal: Return true if s3 is a valid interleaving of s1 and s2, false otherwise.

Input & Output

example_1.py โ€” Valid Interleaving
$ Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
โ€บ Output: true
๐Ÿ’ก Note: s3 can be formed by interleaving s1 and s2. One possible way: a(s1) + a(s1) + d(s2) + b(s1) + b(s2) + c(s1) + b(s2) + c(s1) + a(s2) + c(s2)
example_2.py โ€” Invalid Interleaving
$ Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
โ€บ Output: false
๐Ÿ’ก Note: s3 cannot be formed by any valid interleaving of s1 and s2 while maintaining the relative order of characters within each string
example_3.py โ€” Empty String Case
$ Input: s1 = "", s2 = "", s3 = ""
โ€บ Output: true
๐Ÿ’ก Note: Three empty strings form a valid interleaving (trivial case)

Constraints

  • 0 โ‰ค s1.length, s2.length โ‰ค 100
  • 0 โ‰ค s3.length โ‰ค 200
  • s1, s2, and s3 consist of only lowercase English letters
  • Follow up: Could you solve it using only O(s2.length) extra space?

Visualization

Tap to expand
Interleaving String as Card Shufflings1"aab"s2"dxy"Target s3"aadxby"TTFFTTTFFTTTDP Tables2 โ†’s1โ†“Build DP Tableโœ“Result: Interleaving is possible!
Understanding the Visualization
1
Setup Decks
s1 and s2 are two ordered decks, s3 is the target shuffled deck
2
Build Path Table
Create a grid tracking all possible ways to reach each position
3
Fill Possibilities
For each cell, check if we can arrive from taking the previous card from either deck
4
Trace Result
The bottom-right cell tells us if a valid shuffling exists
Key Takeaway
๐ŸŽฏ Key Insight: Dynamic programming transforms an exponential problem into polynomial time by remembering which positions are reachable, avoiding redundant calculations.
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 24
98.3K Views
Medium-High Frequency
~25 min Avg. Time
2.8K 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