Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

Is a string an interleaving of two others?

Medium · Target 25 minutes · Dynamic programming · Type asked atGoogleMicrosoft

Given strings s1, s2 and s3, return true if s3 can be formed by merging all of s1 and all of s2, taking characters from each in their original order.

Examples

InputOutputWhy
s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"trueaa + dbbc + bc + a + c.
s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"falseNo merge works.
s1 = "", s2 = "", s3 = ""trueEmpty merge.

Constraints

  • 0 ≤ s1.length, s2.length ≤ 100
  • 0 ≤ s3.length ≤ 200

Hints

Hint 1

If the lengths do not add up, the answer is false.

Hint 2

ok[i][j] = can s3[:i + j] be made from s1[:i] and s2[:j]?

Hint 3

ok[i][j] = (ok[i − 1][j] and s1[i − 1] = s3[i + j − 1]) or (ok[i][j − 1] and s2[j − 1] = s3[i + j − 1]).

Where people lose marks

  • Skipping the length check.
  • Merging greedily, which fails when s1 and s2 offer the same next character.
  • Using three indices as the state: k = i + j is determined by the other two.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.