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.
s1ands2have 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.
- 0 <= s1.length, s2.length <= 100
- 0 <= s3.length <= 200
- s1, s2 and s3 consist of lowercase English letters
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 ands1[i − 1]equalss3[i + j − 1]. - Last letter from
s2:ok[i][j − 1]is yes ands2[j − 1]equals that same letter.
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.
Approach
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?
Two ways to store the grid
Keep every row of yes/no answers.
- Easiest to check: each cell reads its own neighbours.
- Keeps history: you can walk back from the corner to see which letter came from which string.
A cell needs only the cell above and the cell to its left, so one row of length n + 1 can be overwritten in place.
- Answers the follow-up: memory grows with
s2only. - Loses history: earlier rows are gone.
Both fill the same cells in the same order in O(m·n) time. The steps, code and live demo use the full table; the one-row version follows the demo.
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.
Start from the empty split
Set ok[0][0] to true: taking nothing from either string builds the empty start of s3.
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.
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.
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.
Code in Python, C++ and Java
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.
Common pitfalls
Taking from s1 whenever its letter matches
if i < m and s1[i] == s3[k]:
i += 1
elif j < n and s2[j] == s3[k]:
j += 1
else:
return Falseif i > 0 and ok[i - 1][j] and s1[i - 1] == s3[k]:
ok[i][j] = TrueWith 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
ok = [[False] * (n + 1) for _ in range(m + 1)]
if m + n != len(s3):
return FalseThe 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.
Edge cases
The lengths agree, ok[0][0] is true and is also the bottom-right cell, so the answer is true.
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.
Complexity
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.