LeetCode #97 Medium

Interleaving String

Interleaving String is LeetCode 97 (Medium). Given strings s1, s2 and s3, decide whether s3 can be made by weaving s1 and s2 together: every letter of both strings is used exactly once, and each string's letters stay in their own order.

  • s1 and s2 have at most 100 letters each, so a table with one cell per pair of lengths, about 10⁴ cells, is cheap.
  • Follow-up: use only O(s2.length) extra memory.
Constraints
  • 0 <= s1.length, s2.length <= 100
  • 0 <= s3.length <= 200
  • s1, s2 and s3 consist of lowercase English letters
dynamic-programmingstring
Open on LeetCode ↗
02

Intuition

Matching letters greedily fails. When the next letter of s3 matches the front of both s1 and s2, either choice might be the dead end, and you cannot tell yet.

So keep every option open. What matters about a partial weave is only how many letters it has used from each string: i from s1 and j from s2, which fixes that the first i + j letters of s3 are done. Cell ok[i][j] records whether that split can be reached.

  • Last letter from s1: ok[i − 1][j] is yes and s1[i − 1] equals s3[i + j − 1].
  • Last letter from s2: ok[i][j − 1] is yes and s2[j − 1] equals that same letter.
How to spot this pattern

Two sequences consumed in order, with a choice at each step of which one to take from, is a two-index grid DP, the same shape as edit distance or longest common subsequence.

03

Approach

Try it first

Before reading on, try s1 = "ab", s2 = "ac", s3 = "acab". The first a of s3 could come from either string. Which choice works? What would a program need to remember so it does not have to guess?

1

Check the lengths first

If len(s1) + len(s2) is not len(s3), return false. Every letter must be used exactly once, so no weave can fix a length mismatch, and the table below would otherwise answer yes while letters of s3 are left over.

2

Start from the empty split

Set ok[0][0] to true: taking nothing from either string builds the empty start of s3.

3

Fill each cell from above and from the left

Go row by row, left to right. Cell (i, j) is true if the cell above is true and s1's letter i − 1 matches s3's letter i + j − 1, or if the cell to the left is true and s2's letter j − 1 matches it. Both neighbours are filled before the cell that needs them.

4

Read the bottom-right cell

ok[m][n] says whether all of s1 and all of s2 can be woven into all of s3, which is the answer.

5

Why one yes or no per cell is enough

Two partial weaves that used the same i letters of s1 and j letters of s2 have exactly the same letters left to place, so nothing later can tell them apart. Keeping one answer per pair replaces trying all the weaves one by one, which grows exponentially.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
▶3 m, n = len(s1), len(s2)
▶4 if m + n != len(s3):
▶5 return False
▶6 ok = [[False] * (n + 1) for _ in range(m + 1)]
▶7 ok[0][0] = True
▶8 for i in range(m + 1):
▶9 for j in range(n + 1):
▶10 k = i + j - 1
▶11 if i > 0 and ok[i - 1][j] and s1[i - 1] == s3[k]:
▶12 ok[i][j] = True
▶13 if j > 0 and ok[i][j - 1] and s2[j - 1] == s3[k]:
▶14 ok[i][j] = True
▶15 return ok[m][n]
s3acabs2 →s1 ↓acab2 + 2 letters = length of s3 → build the grid
m2
n2
The lengths agree, so a weave is possible in principle. Row i, column j of the grid will say whether the first i letters of s1 and the first j of s2 can form the first i + j letters of s3.
s3acabs2 →s1 ↓acabyesnothing taken, nothing built → yes
ok[0][0]yes
Taking no letters from either string builds the empty start of s3, so the top-left cell is yes. Every other cell is reached from it.
s3acabs2 →s1 ↓acabyesyes0 of s1, 1 of s2: 'a' from s2 → yes
i0
j1
s3 lettera
ok[0][1]yes
This cell asks whether 0 letters of s1 and 1 of s2 can form the first 1 of s3. The newest letter, 'a', came either from s1 (cell above) or from s2 (cell to the left). It works s2's 'a' from the left, so yes.
s3acabs2 →s1 ↓acabyesyesyes0 of s1, 2 of s2: 'c' from s2 → yes
i0
j2
s3 letterc
ok[0][2]yes
This cell asks whether 0 letters of s1 and 2 of s2 can form the first 2 of s3. The newest letter, 'c', came either from s1 (cell above) or from s2 (cell to the left). It works s2's 'c' from the left, so yes.
s3acabs2 →s1 ↓acabyesyesyesyes1 of s1, 0 of s2: 'a' from s1 → yes
i1
j0
s3 lettera
ok[1][0]yes
This cell asks whether 1 letter of s1 and 0 of s2 can form the first 1 of s3. The newest letter, 'a', came either from s1 (cell above) or from s2 (cell to the left). It works s1's 'a' from above, so yes.
s3acabs2 →s1 ↓acabyesyesyesyesno1 of s1, 1 of s2: 'c' fits neither way → no
i1
j1
s3 letterc
ok[1][1]no
This cell asks whether 1 letter of s1 and 1 of s2 can form the first 2 of s3. The newest letter, 'c', came either from s1 (cell above) or from s2 (cell to the left). Neither works: s1's 'a' is not 'c', and s2's 'a' is not 'c', so no.
s3acabs2 →s1 ↓acabyesyesyesyesnoyes1 of s1, 2 of s2: 'a' from s1 → yes
i1
j2
s3 lettera
ok[1][2]yes
This cell asks whether 1 letter of s1 and 2 of s2 can form the first 3 of s3. The newest letter, 'a', came either from s1 (cell above) or from s2 (cell to the left). It works s1's 'a' from above, so yes.
s3acabs2 →s1 ↓acabyesyesyesyesnoyesno2 of s1, 0 of s2: 'c' fits neither way → no
i2
j0
s3 letterc
ok[2][0]no
This cell asks whether 2 letters of s1 and 0 of s2 can form the first 2 of s3. The newest letter, 'c', came either from s1 (cell above) or from s2 (cell to the left). Neither works: s1's 'b' is not 'c', so no.
s3acabs2 →s1 ↓acabyesyesyesyesnoyesnono2 of s1, 1 of s2: 'a' fits neither way → no
i2
j1
s3 lettera
ok[2][1]no
This cell asks whether 2 letters of s1 and 1 of s2 can form the first 3 of s3. The newest letter, 'a', came either from s1 (cell above) or from s2 (cell to the left). Neither works: the cell above is no, and the cell to the left is no, so no.
s3acabs2 →s1 ↓acabyesyesyesyesnoyesnonoyes2 of s1, 2 of s2: 'b' from s1 → yes
i2
j2
s3 letterb
ok[2][2]yes
This cell asks whether 2 letters of s1 and 2 of s2 can form the first 4 of s3. The newest letter, 'b', came either from s1 (cell above) or from s2 (cell to the left). It works s1's 'b' from above, so yes.
s3acabs2 →s1 ↓acabyesyesyesyesnoyesnonoyesbottom-right cell is yes → true
answertrue
The bottom-right cell covers all of s1 and all of s2. It is yes, so s3 is an interleaving.
05

One row, reused

Before row[j] is overwritten it still holds the answer from the row above, and row[j − 1] already holds the new answer to the left. Those are exactly the two neighbours a cell needs.

▶1class Solution:
▶2 def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
▶3 m, n = len(s1), len(s2)
▶4 if m + n != len(s3):
▶5 return False
▶6 row = [False] * (n + 1)
▶7 for i in range(m + 1):
▶8 for j in range(n + 1):
▶9 if i == 0 and j == 0:
▶10 row[j] = True
▶11 continue
▶12 k = i + j - 1
▶13 from_up = i > 0 and row[j] and s1[i - 1] == s3[k]
▶14 from_left = j > 0 and row[j - 1] and s2[j - 1] == s3[k]
▶15 row[j] = from_up or from_left
▶16 return row[n]
06

Common pitfalls

Taking from s1 whenever its letter matches

✗ Wrong
if i < m and s1[i] == s3[k]:
    i += 1
elif j < n and s2[j] == s3[k]:
    j += 1
else:
    return False
✓ Right
if i > 0 and ok[i - 1][j] and s1[i - 1] == s3[k]:
    ok[i][j] = True

With s1 = "ab", s2 = "ac", s3 = "acab", the greedy loop takes the first a from s1, then finds c at neither front and says no. Taking ac from s2 first and then ab from s1 works, so the answer is yes.

Skipping the length check

✗ Wrong
ok = [[False] * (n + 1) for _ in range(m + 1)]
✓ Right
if m + n != len(s3):
    return False

The table only reads the first m + n letters of s3. With s1 = "a", s2 = "", s3 = "ab", it fills ok[1][0] with yes and returns true, though b was never used.

07

Edge cases

All three strings empty

The lengths agree, ok[0][0] is true and is also the bottom-right cell, so the answer is true.

One input empty, e.g. s1 = ""

The table has one row, and each cell can only come from the left, so the answer is true exactly when s2 equals s3.

08

Complexity

Time
O(m·n)
Space
O(m·n)
One constant-time check per cell of an (m + 1) by (n + 1) table. The one-row version below keeps the same time and needs O(n) memory, which is the follow-up.
09

Interleaving String FAQ

Can I use recursion with memoization instead?

Yes. Write a function of (i, j) that tries to take the next letter from s1, then from s2, and cache each pair's result. It visits the same (m + 1)(n + 1) states, and the recursion depth is at most m + n, which is 200 here. Make sure the cache can tell "not computed" apart from a stored false.

Why is counting the letters not enough?

Counts confirm that s3 has the right letters, not that they come in a usable order. "ab" and "cd" have the same letters as "bacd", yet b cannot come before a, so it is not an interleaving.