oneby7

2-D Dynamic Programming Two strings

563. Interleaving String

Medium

You are given three strings, s1, s2 and s3. Return true if s3 is an interleaving of s1 and s2, and false otherwise.

s3 is an interleaving of s1 and s2 when we can build it one letter at a time, each time taking the next unused letter of s1 or the next unused letter of s2, until both strings are used up. So s3 uses every letter of both strings exactly once, and the letters of each string stay in their order. We may take as many letters in a row from one string as we like.

Any of the three strings can be empty.

Example 1

Input: s1 = "bat", s2 = "ball", s3 = "babtall"

Output: true

Explanation: Take b and a from s1, then b from s2, then t from s1, and last a, l and l from s2.

Example 2

Input: s1 = "", s2 = "sun", s3 = "sun"

Output: true

Explanation: With s1 empty, s3 has to be s2 itself, and it is.

Example 3

Input: s1 = "abc", s2 = "xyz", s3 = "axbzcy"

Output: false

Explanation: Every letter is different, so each letter of s3 can come from only one string. s3 has z before y, but in s2 the y comes first.

Check your understanding

Work out the answer for this input before you write any code.

s1 = "ab", s2 = "ac", s3 = "acab"

Constraints

  • 0 ≤ s1.length, s2.length ≤ 3000
  • 0 ≤ s3.length ≤ 6000
  • s1, s2 and s3 hold only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.