Interleaving String
Problem
Given three strings s1, s2, and s3, decide whether s3 can be formed by merging s1 and s2 so that every character of both is used exactly once and the characters of each original string appear in s3 in their original relative order. The two sources may alternate arbitrarily.
- Each of the two source strings is up to 120 characters.
- The combined target string is up to 240 characters.
- All strings consist of lowercase English letters.
Examples
s1 = "xxbcc", s2 = "dccbx", s3 = "xdxccbcbcx"→true. One valid split isx|d|x|cc|bc|b|c|xwith segments alternating between s1 and s2.s1 = "xxbcc", s2 = "dccbx", s3 = "bcxxbccdcx"→false.s3starts withb, but neithers1nors2begins withb, so no interleaving can produce this string.s1 = "", s2 = "", s3 = ""→true. Three empty strings interleave trivially.
Hints
- Suppose you have used the first
icharacters ofs1and the firstjcharacters ofs2. Which position ofs3are you at? Which character must come next? - When
s1[i]ands2[j]are both equal to the next character ofs3, you cannot decide greedily. Keep both options alive. dp[i][j]= cans3[:i+j]be formed froms1[:i]ands2[:j]. Each cell comes from the cell above or the cell to the left.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.