InterviewPrepKit

Home / Coding / 2-D Dynamic Programming

Interleaving String

medium Original β†—
Solving tips
  • First guard: if len(s1)+len(s2) != len(s3) return False immediately, since no interleaving can exist.
  • Model the state as (i,j) = characters consumed from s1 and s2; their sum pins the position in s3, giving a boolean reachability grid dp[i][j].
  • Recurrence: dp[i][j] is True if you just took s1[i-1] (dp[i-1][j] and s1[i-1]==s3[i+j-1]) or just took s2[j-1] (dp[i][j-1] and s2[j-1]==s3[i+j-1]).
  • Pitfall: greedily picking whichever source matches fails when both match; you must consider both branches (DP does this automatically). Target O(m*n) time, O(n) space.

Problem

Given three strings s1, s2, and s3, decide whether s3 can be formed by interleaving s1 and s2. An interleaving weaves the two strings together while keeping the internal order of each one intact β€” you repeatedly take the next character from either s1 or s2 until both are exhausted.

Return True if such an interleaving produces exactly s3, else False.

Examples

  • s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" β†’ True β€” one weave: aa(s1) dbbc(s2) b(s1) c(s1)… the characters of each source appear in order inside s3.
  • s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" β†’ False β€” no weave of the two produces this string.
  • s1 = "", s2 = "", s3 = "" β†’ True β€” two empty strings interleave to empty.

Constraints

  • 0 <= s1.length, s2.length <= 100
  • 0 <= s3.length <= 200
  • All strings consist of lowercase English letters.

If len(s1) + len(s2) != len(s3), the answer is immediately False. Otherwise the expected solution is O(m Γ— n).

Think about it first

Hint 1 Build `s3` left to right. To place its next character you must consume it from the front of whatever remains of `s1` or `s2` β€” and only if that front character matches. This is a two-pointer choice at every step.
Hint 2 Greedily picking whichever matches can fail β€” sometimes both match and only one choice leads to a full solution. Track the state `(i, j)` = "we've used `i` characters of `s1` and `j` of `s2`," which fixes that we've filled the first `i + j` characters of `s3`. That's a 2-D table.
Hint 3 `dp[i][j]` = can `s3[:i+j]` be formed from `s1[:i]` and `s2[:j]`? It's reachable if either you just took `s1[i-1]` (so `dp[i-1][j]` was true and `s1[i-1] == s3[i+j-1]`) or you just took `s2[j-1]` (so `dp[i][j-1]` and `s2[j-1] == s3[i+j-1]`). Base `dp[0][0] = True`.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.