Python 0097.py
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
if len(s1) + len(s2) != len(s3):
return False
LAST = "|"
s1 += LAST
s2 += LAST
@cache
def deeper(a, b):
c = a + b
if c == len(s3):
return True
if s3[c] == s1[a] and s3[c] == s2[b]:
return deeper(a+1, b) or deeper(a, b+1)
if s3[c] == s1[a]:
return deeper(a+1, b)
if s3[c] == s2[b]:
return deeper(a, b+1)
return False
return deeper(0, 0)
Difficulty
and has an acceptance rate of about 44% (1+ million submissions).
Typical patterns to solve this problem:
- Dynamic Programming
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a method that determines whether a target string can be formed by interleaving two source strings while preserving the relative order of characters from each source. The algorithm first validates the basic length requirement, then augments the source strings with a sentinel character to simplify boundary handling. A depth-first search with memoization explores all feasible ways to consume characters from the two sources, returning true as soon as a complete match is found.
Key Steps
The first logical step checks that the combined length of the two source strings equals the length of the target. This guards against impossible cases early in the execution flow.
if len(s1) + len(s2) != len(s3):
return False
Next, a sentinel character ("|") is appended to each source string. By placing a unique marker beyond the normal alphabet, the algorithm can safely reference the next character even when the index reaches the original end of a string.
LAST = "|"
s1 += LAST
s2 += LAST
The core of the solution is a nested recursive function named deeper. It is decorated with @cache, which automatically memoizes results for each pair of indices, preventing repeated work for identical sub-problems.
@cache
def deeper(a, b):
c = a + b
if c == len(s3):
return True
...
Inside deeper, the variable c represents the current position in the target string, derived from the sum of characters already taken from both sources. When c reaches the length of the target, the recursion has successfully consumed the entire string, and the function returns True.
The matching logic proceeds by comparing the current target character with the characters at the current indices of the two source strings. If the target character matches both sources, the recursion branches, trying both possibilities. If it matches only one source, the recursion follows that single path. If there is no match, the function returns False.
if s3[c] == s1[a] and s3[c] == s2[b]:
return deeper(a+1, b) or deeper(a, b+1)
if s3[c] == s1[a]:
return deeper(a+1, b)
if s3[c] == s2[b]:
return deeper(a, b+1)
return False
Finally, the outer method initiates the search from the start of both source strings.
return deeper(0, 0)
Edge Cases Handled
When the lengths of the inputs do not satisfy the necessary condition, the method exits immediately, handling mismatched length scenarios without further computation.
Appending the sentinel character ensures that attempts to access s1[a] or s2[b] after the original strings have been exhausted do not raise an index error. The sentinel is distinct from any valid input character, so it never falsely satisfies a match condition.
If both source strings are empty, the length check passes only when the target is also empty, leading the recursion to hit the base case (c == len(s3)) instantly and return True.
When the target character matches both sources simultaneously, the algorithm explores both continuation paths, guaranteeing that any valid interleaving that diverges at that point will be discovered.
Performance Optimizations
Memoization via the @cache decorator eliminates redundant exploration of identical index pairs. Each unique combination of positions in the two source strings is evaluated at most once, converting the exponential branching of a naïve depth-first search into a bounded number of sub-problem evaluations.
The sentinel technique removes the need for explicit boundary checks before each character comparison, allowing the core matching logic to remain concise and avoiding extra conditional branches that could degrade execution speed.
Early termination is built into the recursion: as soon as a complete match is found (c == len(s3)), the function returns True without further descent, preventing unnecessary work after a successful path has been identified.
Overall, the combination of length pre-validation, sentinel usage, and cached recursion yields an implementation that explores the solution space efficiently while maintaining clear and straightforward control flow.
ELI5 - Simplified Explanation
Imagine having two stacks of colorful building blocks named s1 and s2. Both stacks have special letters written on them. There is also a third stack called s3 that has a mix of letters from the first two. The goal is to see if s3 was made by taking blocks from the first two stacks one by one without ever changing the order the letters appeared in their original piles.
The code first checks if the number of blocks in the first two piles adds up to the number of blocks in the final pile. If the total number of blocks does not match, then it is impossible to make s3, so the process stops right away.
To help keep track of where the letters are, the code adds a secret marker to the end of the first two piles. Think of this marker like a little sign that says the pile is finished.
The computer then starts a game called deeper. This game looks at the first letter of the third pile and asks if it came from the first pile or the second pile. If the letter is found at the top of either pile, the computer remembers that spot and moves to the next letter in the pile it chose. It keeps doing this, jumping back and forth between the two piles to match every single letter in s3. If the computer reaches the end of the third pile successfully, it means everything fits perfectly. The computer is very smart because it uses a memory trick called cache, which helps it remember paths it has already checked so it does not have to do the same work twice.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | C# | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | Python | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JS | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| martianoff | Scala | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | Python, Python | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| chenyanzhe | C++ | ||||||||||
| everthis | JavaScript | ||||||||||
| FelixFan1122 | C# | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| Garvit244 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| martianoff | Scala | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 230: Kth Smallest Element in a BST
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality