You are given three strings, s1, s2 and s3. Decide whether s3 can be made by interleaving s1 and s2: taking all the letters of both, each string's letters staying in their own order, and merging them into one sequence.
Think of two decks of cards shuffled together once: you may take the next card from either deck at any moment, but you can never reorder a deck. Return true if some way of choosing gives exactly s3, and false otherwise.
Example 1
Input: s1 = "ab", s2 = "cb", s3 = "acbb" Output: true Why: a from s1, c from s2, b from s1, b from s2
2 more examples and the constraints
Example 2
Input: s1 = "ab", s2 = "cb", s3 = "abbc" Output: false Why: after "ab" from s1, s2 would have to give "bc", but it is "cb"
Example 3
Input: s1 = "", s2 = "xy", s3 = "xy" Output: true Why: everything comes from s2
Constraints
- 0 ≤ length of s1, length of s2 ≤ 100
- 0 ≤ length of s3 ≤ 200
- All three strings use lower-case English letters only
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try both choicesO(2^(m+n))
- Recursion with a memoO(m·n)
- Bottom-up DP tableO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two strings of 100 letters | Verdict |
|---|---|---|---|
| Try both choices | O(2^(m+n)) | Explodes on repeated letters | |
| Recursion with a memo | O(m·n) | Passes; easy step from brute | |
| Bottom-up DP table | O(m·n) | Best; no recursion, can shrink to a row |
m = length of s1, n = length of s2.
Edge cases to test
- Lengths do not add up. "a", "b", "abc" is false before any other work.
- Empty strings. Three empty strings give true; two empty strings and a non-empty s3 give false.
- One string empty. Then s3 must equal the other string exactly.
- Same letters in both strings. "abc", "abc", "aabbcc": a greedy choice can go wrong, so both options must be kept.
Common mistakes
- Choosing greedily from whichever string matches first, which fails when both match.
- Skipping the length check, so the table can say true when s3 has extra letters.
- Indexing s3 with
iorjalone instead ofi + j − 1.
How to talk through it
- 1Clarify. Must all letters of both strings be used? Can any of the strings be empty?
- 2Give the brute force. At each letter, try taking it from s1 or from s2; say it can branch two ways every time.
- 3Find the state. Only (i, j) matters: how many letters you have used from each. That gives (m + 1) × (n + 1) states.
- 4Code the table. Explain the two ways into
dp[i][j], from above with s1's letter, or from the left with s2's. - 5Test out loud. Run the length mismatch, an empty string and the repeated-letter case.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?