Python 0087.py
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
@cache
def deeper(a, b):
# early exit
if a == b:
return True
if sorted(a) != sorted(b):
return False
for i in range(1, len(a)):
# no swap
if deeper(a[:i], b[:i]) and deeper(a[i:], b[i:]):
return True
# swap
swapped = a[i:] + a[:i]
p = len(a) - i
if deeper(swapped[:p], b[:p]) and deeper(swapped[p:], b[p:]):
return True
return False
return deeper(s1, s2)
Difficulty
and has an acceptance rate of about 45% (700k+ 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 solves the classic “scramble string” problem using a recursive depth-first search combined with memoization. The public method isScramble receives two strings and delegates the actual work to an inner helper deeper. The helper explores all possible ways to split the strings and checks both the non-swapped and swapped configurations. Early termination is achieved through direct equality checks and character-frequency comparison, while the @cache decorator eliminates redundant recomputation of identical sub-problems.
Core Logic
Early Equality Check
if a == b:
return True
When the two substrings are identical, the function returns immediately, avoiding any further recursion. This handles the trivial case where the strings are already in the required order.
Character Frequency Pruning
if sorted(a) != sorted(b):
return False
By sorting both substrings and comparing the results, the algorithm discards branches where the multiset of characters differs. This prevents unnecessary deeper exploration for impossible matches, such as when one substring contains a character that the other does not.
Recursive Partitioning
for i in range(1, len(a)):
# no swap
if deeper(a[:i], b[:i]) and deeper(a[i:], b[i:]):
return True
# swap
swapped = a[i:] + a[:i]
p = len(a) - i
if deeper(swapped[:p], b[:p]) and deeper(swapped[p:], b[p:]):
return True
The loop iterates over every possible split position i. For each position, two scenarios are examined:
- The left part of
aaligns with the left part ofband the right parts align correspondingly. - The left part of
ais moved to the end (producingswapped), and the new left part ofswappedaligns with the left part ofb.
If either scenario yields a pair of recursive calls that both return True, the current call returns True as well, indicating a valid scramble configuration.
Default Failure
return False
If none of the split positions produce a successful match, the function concludes that the substrings cannot be scrambled into each other and returns False.
Edge Cases Handled
The algorithm gracefully handles empty strings because the outer loop never executes when the length is zero, and the early equality check will return True only when both inputs are empty. Single-character strings are also covered: the equality check succeeds if the characters match, otherwise the sorted comparison fails, leading to a False result.
When the two strings contain the same characters but in different orders, the sorted comparison passes, allowing the recursive partitioning to explore all possible rearrangements. The swap logic correctly addresses cases where a valid scramble requires swapping the two halves at some recursion depth, such as transforming "great" into "rgeat".
Performance Optimizations
The most significant optimization is the use of the @cache decorator from the functools module. By memoizing the results of deeper(a, b), the implementation avoids recomputing the same substring pair multiple times, which dramatically reduces the exponential blow-up typical of naïve recursive solutions.
The early equality and sorted checks act as cheap filters that prune large portions of the recursion tree before any deeper calls are made. This reduces the number of cached entries and the overall number of recursive invocations.
The construction of the swapped string (a[i:] + a[:i]) is performed only when the non-swap scenario fails for a particular split, ensuring that the extra concatenation cost is incurred only when necessary.
Together, these techniques keep the algorithm efficient enough to handle moderate-size inputs within reasonable time limits.
ELI5 - Simplified Explanation
Imagine there are two blocks filled with letters. To see if one pile of blocks can turn into the other, the computer plays a matching game. It first looks to see if the letters are the same in both piles, because if they are different, it is impossible for them to match.
The computer then takes a deep breath and looks for a place to cut the pile into two smaller pieces. It tries two different approaches. In the first approach, it keeps the pieces in the same order and checks if the smaller parts match up. If that does not work, it tries a second approach where it swaps the pieces around, putting the back part in front, to see if that creates a match instead.
Whenever the computer finds a way to cut and perhaps flip the piles so that they look identical, it feels happy because it knows the two piles are related. If it tries every possible cut and every possible swap and still nothing matches, then it decides the piles are just too different to be the same. The cache helps the computer remember the answers it already found so it does not have to do the same hard work over and over again.
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 | Python | C++ | Java | TS | |||||
| WalkCCC | Python | C++ | Java | |||||||
| leetcode.ca | Python | C++ | Java | C# | Go | TS | ||||
| LeetcodeHelp | Python | C++ | Java | |||||||
| MemoryLimitExceeded | Python | C++ | ||||||||
| Progiez | Python | C++ | Java | |||||||
| github | aylei | Rust | ||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | Python | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JS | |||||||||
| gaosq0604 | Python | |||||||||
| Garvit244 | Python | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| aylei | Rust | |||||||||
| begeekmyfriend | C | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | Python, Python | |||||||||
| charles-wangkai | Java | |||||||||
| chenyanzhe | C++ | |||||||||
| everthis | JavaScript | |||||||||
| gaosq0604 | Python | |||||||||
| Garvit244 | Python | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| lzl124631x | C++ | |||||||||
| qiyuangong | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| vthwang | Java | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | 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 97: Interleaving String
- 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 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