Interleaving String
LeetCode 97 · Medium · solution, intuition & step-by-step walkthrough
State (i, j) — k is always i + j, so only two indices matter.
This is how I solved Interleaving String (LeetCode 97), a medium problem from the String DP / Word Break pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Walk s3 one character at a time. The next character must come from the front of what's left of s1 or of s2. If it matches one, advance that string; if it matches both, try both. Memoising on the two positions removes the exponential branching.
Approach
- 1
Lengths must add up, otherwise it's impossible.
- 2
If s1 is used up, the rest of s2 must equal the rest of s3 (and vice versa).
- 3
If s1[i] == s3[k], try advancing s1; if s2[j] == s3[k], try advancing s2.
- 4
Return True if either branch succeeds; lru_cache stores each (i, j, k).
How I solved it
Recursion + memoPythonO(m·n) time · O(m·n) space
from functools import lru_cache
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
if len(s1)+len(s2)!=len(s3):
return False
@lru_cache(maxsize=None)
def dfs(i,j,k):
if i==len(s1):
return s2[j:]==s3[k:]
if j==len(s2):
return s1[i:]==s3[k:]
case1=False
case2=False
if s1[i]==s3[k]:
case1 = dfs(i+1,j,k+1)
if s2[j]==s3[k]:
case2 = dfs(i,j+1,k+1)
return case1 or case2
return dfs(0,0,0)Interleaving String — FAQ
What is the intuition behind Interleaving String?
Walk s3 one character at a time. The next character must come from the front of what's left of s1 or of s2. If it matches one, advance that string; if it matches both, try both. Memoising on the two positions removes the exponential branching.
How do you solve Interleaving String (LeetCode 97)?
1. Lengths must add up, otherwise it's impossible. 2. If s1 is used up, the rest of s2 must equal the rest of s3 (and vice versa). 3. If s1[i] == s3[k], try advancing s1; if s2[j] == s3[k], try advancing s2. 4. Return True if either branch succeeds; lru_cache stores each (i, j, k).
What is the time and space complexity of Interleaving String?
Time: O(m · n). Space: O(m · n). (Accepted approach: Recursion + memo.)
What are common mistakes in Interleaving String?
Greedy 'take from s1 when it matches' fails when both strings share a character. Check the length sum first — it prunes many inputs instantly.