hardDynamic ProgrammingDynamic Programming

Interleaving String

hardTime: O(m*n)Space: O(m*n)

Signals to notice

interleave two strings to form a thirdorder within each string preservedtwo source pointers

Brute force first

Recursively try taking the next character from s1 or s2. Two choices at each position, exponential branching. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

2D DP: dp[i][j] = can the first i chars of s1 and first j chars of s2 form the first (i+j) chars of s3? Check if s3[i+j-1] matches s1[i-1] (extend from dp[i-1][j]) or s2[j-1] (extend from dp[i][j-1]). Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

What must stay true

Position (i,j) in the DP table corresponds to having consumed i characters from s1 and j characters from s2, matching s3[0.i+j-1]. The next character in s3 must come from either s1 or s2. As long as that statement keeps holding, you can trust the steps built on top of it.

Easy way to go wrong

Forgetting to check s1.length + s2.length == s3.length first — if lengths don't add up, interleaving is impossible regardless. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Dynamic Programming Pattern