InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 2-D Dynamic Programming

Interleaving String

medium Original ↗ 00:00

Problem

Given three strings s1, s2, and s3, decide whether s3 can be formed by interleaving s1 and s2. An interleaving merges the two strings while preserving the internal order of each: at each step you take the next character from either s1 or s2, until both are exhausted.

Return True if some interleaving produces exactly s3, else False.

Examples

  • s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"True. The characters of s1 and of s2 each appear in their original order inside s3.
  • s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"False. No interleaving of the two produces this string.
  • s1 = "", s2 = "", s3 = ""True. Two empty strings interleave to the empty string.

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. Its next character must come from the front of what remains of `s1` or `s2`, and only if that front character matches. So each step is a choice between two pointers.
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)` = "used `i` characters of `s1` and `j` of `s2`". This fixes that the first `i + j` characters of `s3` are filled, giving a 2-D table.
Hint 3 `dp[i][j]` = can `s3[:i+j]` be formed from `s1[:i]` and `s2[:j]`? It is reachable if the last character came from `s1` (`dp[i-1][j]` is true and `s1[i-1] == s3[i+j-1]`) or from `s2` (`dp[i][j-1]` is true and `s2[j-1] == s3[i+j-1]`). Base case `dp[0][0] = True`.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug