Skip to main content

Interleaving String

Check if s3 is formed by interleaving s1 and s2 Example: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac" => true Interleaving: "aa" + "dbbc" + "bc" + "a" + "c" Example: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc" => false

Given strings s1, s2, and s3, return a boolean indicating whether s3 can be formed using every character of s1 and s2 exactly once while preserving the order of characters within each source string. Characters from the two sources may be mixed in any way that preserves those orders. Return false if the length of s3 differs from the sum of the source lengths. Empty strings are allowed, and three empty strings return true.

Examples

You write

is_interleave(s1: str, s2: str, s3: str)

  1. Example 1

    Input
    s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
    returns
    true
  2. Example 2

    Input
    s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
    returns
    false

The pattern behind it

Dynamic Programming

I reach for it when

  • Brute force repeats the same subproblem.
  • You are asked for a count, a minimum or a maximum.

Say this before you type. Say the state in one sentence, then say which smaller states it reads from.

All 37 Dynamic Programming problems

Strings

I reach for it when

  • The input is text and the answer is a count, a substring or a new string.
  • You need to compare, reverse or rebuild characters.

Say this before you type. Say which array pattern the string is hiding before you touch a character.

All 51 Strings problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Check If String Is Interleavedmedium