Interleaving String

Medium

Topics
StringDynamic Programming

Given strings s1, s2, and s3, return true if s3 is formed by an interleaving of s1 and s2 (preserving the order of each).

Example 1

s1aabcc
s2dbbca
s3aadbbcbcac
from s1from s2
Every character of s3 is traced back to the string it came from, and within each source the characters keep their original order — only the two sources are shuffled together. Since that is possible here, the answer is true.
The two sources and the string they are meant to interleave into.
Input:  s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Example 2

s1aabcc
s2dbbca
s3aadbbbaccc
No way of shuffling s1 and s2 together, keeping each one’s characters in order, produces s3 — so the answer is false. Note that the lengths alone must add up before anything else can.
Input:  s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

Constraints

  • 0 <= s1.length, s2.length <= 100
  • s3.length == s1.length + s2.length
  • Inputs are lowercase letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Let dp[i][j] mean the first i chars of s1 and first j of s2 can interleave to form the first i+j chars of s3. Each step consumes one char from s1 or s2 if it matches the next char of s3.

Approach

  1. If lengths do not add up, return false.
  2. dp[0][0] = true. dp[i][j] is true if (s1[i-1]==s3[i+j-1] and dp[i-1][j]) or (s2[j-1]==s3[i+j-1] and dp[i][j-1]).
  3. Answer is dp[m][n].

Dry Run

s1 = "aabcc"   s2 = "dbbca"   s3 = "aadbbcbcac"
dp[i][j] = "the first i of s1 and the first j of s2 interleave to the first i+j of
s3". The index into s3 is implied by i + j, which is why no third dimension is
needed.
        ""   d   b   b   c   a
  ""     T   .   .   .   .   .
  a      T   .   .   .   .   .
  a      T   T   T   T   T   .
  b      .   T   T   .   T   .
  c      .   .   T   T   T   T
  c      .   .   .   T   .   T
answer dp[5][5] = true
Each true cell is reachable from above (take the next character of s1) or from the
left (take the next of s2), and only if that character matches s3 at position
i + j - 1. The Ts wander diagonally across the table, which is the picture of the
two strings alternating.
Greedy does not work, and this input shows exactly where it goes wrong. A
"prefer s1 whenever it matches" walk agrees for the first three characters and
then diverges at s3[3] = 'b', taking it from s1 because s1[2] is also 'b'. It
keeps going and gets stuck at s3[8] = 'a' with s1 exhausted and s2 offering a 'c'.
The valid split takes that 'b' from s2 instead:
  "aa" from s1, then "dbbc" from s2, then "bc" from s1, then "a" from s2, then "c"
Which string supplies a character cannot be decided locally, because both can
match and only one choice survives nine characters later. That is the whole reason
for the table.
Note row b column b is false while its neighbours are true. Being reachable is not
inherited; each cell needs its own matching character, which is what stops the
table filling in uniformly.

Complexity

  • Time — O(m*n): fill the table once.
  • Space — O(m*n): the DP grid (reducible to O(n)).

Common Pitfalls

  • A greedy char-by-char match fails; you need the full DP because either string could supply the next char.

Full Solution — all languages

class Solution:
    def isInterleave(self, s1, s2, s3):
        m,n=len(s1),len(s2)
        if m+n!=len(s3): return False
        dp=[[False]*(n+1) for _ in range(m+1)]
        dp[0][0]=True
        for i in range(m+1):
            for j in range(n+1):
                if i>0 and s1[i-1]==s3[i+j-1] and dp[i-1][j]: dp[i][j]=True
                if j>0 and s2[j-1]==s3[i+j-1] and dp[i][j-1]: dp[i][j]=True
        return dp[m][n]
Asked at eBay
SensAI
Beta
Tap the mic to stop voice mode