Gotcha—LeetCode 97: Interleaving String (given s1, s2, s3, decide if s3 can be formed by interleaving s1 and s2 while preserving the relative order of chars from each).
Key idea
At any prefix (i, j) of (s1, s2), we ask if it can form prefix i+j of s3.
Transition: if s1[i-1] == s3[i+j-1] we can come from (i-1, j); if s2[j-1] == s3[i+j-1] we can come from (i, j-1).
First quick check: len(s1) + len(s2) == len(s3) — otherwise False.
User
yes
Assistant
Great—let’s walk the classic example:
s1 = "aabcc"
s2 = "dbbca"
s3 = "aadbbcbcac" (len check: 5 + 5 = 10 ✅)
We’ll build a 2D DP where dp[i][j] = can s1[:i] and s2[:j] interleave to make s3[:i+j].
Base: dp[0][0] = True.
Transition:
If s1[i-1] == s3[i+j-1], we can come from dp[i-1][j].
If s2[j-1] == s3[i+j-1], we can come from dp[i][j-1].
Fill first row/column
dp[i][0] stays True while s1[:i] == s3[:i] → aa matches first two of s3 → dp[1][0]=True, dp[2][0]=True, then stops.
dp[0][j] requires s2[:j] == s3[:j] → first char mismatches (d vs a) → all False after dp[0][0].
Completed table (T/F)
Rows = i over s1 (including empty prefix), Cols = j over s2:
rCopyEdit j: 0 1 2 3 4 5
"" d b b c a
i=0 "" [ T, F, F, F, F, F ]
i=1 a [ T, F, F, F, F, F ]
i=2 a [ T, T, T, T, T, F ]
i=3 b [ F, T, T, F, T, F ]
i=4 c [ F, F, T, T, T, T ]
i=5 c [ F, F, F, T, F, T ] ← dp[5][5] = True
User
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
if len(s1) + len(s2) != len(s3):
return False
code
@cache
def get_sub_strings(i, j, k):
if i == len(s1) and j == len(s2) and k == len(s3):
return True
if i < len(s1) and s1[i] == s3[k]:
if get_sub_strings(i + 1, j, k + 1):
return True
if j < len(s2) and s2[j] == s3[k]:
if get_sub_strings(i, j + 1, k + 1):
return True
return False
return get_sub_strings(0, 0, 0)
explain my code
Assistant
Here’s what your code is doing, step-by-step:
Purpose
It checks if s3 can be formed by interleaving s1 and s2 without changing the order of characters from either string.
@cache (from functools) stores results for each (i, j, k) so you don’t recompute the same subproblem.
User
can you rewrite with memoization, without using cache
Assistant
Sure — here’s your code rewritten to use a plain Python dictionary for memoization instead of @cache:
pythonCopyEditclass Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
if len(s1) + len(s2) != len(s3):
return False
code
memo = {} # key: (i, j), value: True/False
def dfs(i, j):
# k is always i + j
k = i + j
if i == len(s1) and j == len(s2):
return True
if (i, j) in memo:
return memo[(i, j)]
# Try to take from s1
if i < len(s1) and s1[i] == s3[k]:
if dfs(i + 1, j):
memo[(i, j)] = True
return True
# Try to take from s2
if j < len(s2) and s2[j] == s3[k]:
if dfs(i, j + 1):
memo[(i, j)] = True
return True
memo[(i, j)] = False
return False
return dfs(0, 0)
@lru_cache(None)
def dfs(i, j):
k = i + j
if k == len(s3):
return True
ok = False
if i < len(s1) and s1[i] == s3[k]:
ok = ok or dfs(i+1, j)
if j < len(s2) and s2[j] == s3[k]:
ok = ok or dfs(i, j+1)
return ok
return dfs(0, 0)
Time: O(len1 * len2) (each (i,j) solved once)
Space: O(len1 * len2) for memo (call stack up to len1+len2)
Solution B: 2D DP (bottom-up)
pythonCopyEditdef isInterleave(s1: str, s2: str, s3: str) -> bool:
n1, n2 = len(s1), len(s2)
if n1 + n2 != len(s3): return False
dp = [[False]*(n2+1) for _ in range(n1+1)]
dp[0][0] = True
for i in range(1, n1+1):
dp[i][0] = dp[i-1][0] and s1[i-1] == s3[i-1]
for j in range(1, n2+1):
dp[0][j] = dp[0][j-1] and s2[j-1] == s3[j-1]
for i in range(1, n1+1):
for j in range(1, n2+1):
k = i+j-1
dp[i][j] = (dp[i-1][j] and s1[i-1] == s3[k]) or
(dp[i][j-1] and s2[j-1] == s3[k])
return dp[n1][n2]
Time: O(n1n2)
Space: O(n1n2)
Solution C: 1D DP (space-optimized)
pythonCopyEditdef isInterleave(s1: str, s2: str, s3: str) -> bool:
n1, n2 = len(s1), len(s2)
if n1 + n2 != len(s3): return False
dp = [False]*(n2+1)
dp[0] = True
for j in range(1, n2+1):
dp[j] = dp[j-1] and s2[j-1] == s3[j-1]
for i in range(1, n1+1):
dp[0] = dp[0] and s1[i-1] == s3[i-1]
for j in range(1, n2+1):
k = i + j - 1
dp[j] = (dp[j] and s1[i-1] == s3[k]) or (dp[j-1] and s2[j-1] == s3[k])
return dp[n2]
Want me to walk through one example step-by-step with the DP table?
A few key transitions (examples):
dp[2][1] checks s3[2] = 'd':
from left dp[2][0] and s2[0]='d' matches ⇒ True.
dp[3][2] checks s3[4] = 'b':
from up dp[2][2] and s1[2]='b' matches ⇒ True.
dp[5][3] checks s3[7] = 'c':
from left dp[5][2] or from up dp[4][3] with s1[4]='c' matching ⇒ True.
Final dp[5][5] = True ⇒ interleaving is possible.
One valid interleaving (who contributed each s3[k])
Index k: 0 1 2 3 4 5 6 7 8 9
s3 chars: a a d b b c b c a c
pick from: s1 s1 s2 s1 s2 s1 s2 s2 s2 s1
s1 used in order: a, a, b, c, c
s2 used in order: d, b, b, c, a
That preserves the relative order inside each source string, so s3 is an interleaving. Want me to do the same walkthrough for the negative example ("aadbbbaccc") so you can see exactly where the table blocks?
i → current index in s1
j → current index in s2
k → current index in s3 (always i + j if lengths match up so far)
Base case
pythonCopyEditif i == len(s1) and j == len(s2) and k == len(s3):
return True
If we’ve consumed all characters from all three strings at the same time, we have a valid interleaving.
Recursive choices
pythonCopyEditif i < len(s1) and s1[i] == s3[k]:
if get_sub_strings(i + 1, j, k + 1):
return True
If there are characters left in s1 and s1[i] matches the next needed char in s3,
we advance in both s1 and s3.
pythonCopyEditif j < len(s2) and s2[j] == s3[k]:
if get_sub_strings(i, j + 1, k + 1):
return True
Similarly for s2.
Failure path
pythonCopyEditreturn False
If neither choice leads to success, return False.
Return final result
pythonCopyEditreturn get_sub_strings(0, 0, 0)
Starts the recursion from the beginning of all three strings.
Complexity
Time: O(len(s1) * len(s2))
You only visit each (i, j) pair once (because k = i + j).
Space: O(len(s1) * len(s2)) for the memoization table + recursion stack.
💡 Possible simplification:
Since k is always i + j, you don’t need to store it in the cache key — you could cache on (i, j) only. This would slightly reduce memory usage.
If you want, I can rewrite your code in that simpler (i, j) form and show how it runs on an example so you can see the call tree. Would you like me to do that?
Changes from your original code:
Removed @cache
Used memo dictionary keyed by (i, j) — no need to store k because k = i + j.
Slightly simplified the base case (k is implicit).
Added memo lookups and stores explicitly.
This runs in the same O(len(s1) * len(s2)) time and space as your cached version, but it’s easier to control and debug since you can inspect memo at any time.
If you want, I can also walk you through exactly how this memo table fills up for the "aabcc", "dbbca", "aadbbcbcac" example so you can see the order of exploration. Would you like me to do that?