Scramble String - Problem
Imagine you have a string and you want to scramble it using a specific recursive algorithm. The scrambling process works like this:
- If the string has only 1 character, stop (base case)
- If the string has more than 1 character:
- Split the string into two non-empty parts at any position
- Randomly decide whether to swap these two parts or keep them in order
- Apply this scrambling process recursively to each part
For example, starting with "great":
- Split into
"gr"+"eat", then swap →"eatgr" - Recursively scramble
"eat"→ might become"tea" - Recursively scramble
"gr"→ might become"rg" - Final result:
"tearg"
Your task: Given two strings s1 and s2 of the same length, determine if s2 is a scrambled version of s1.
Input & Output
example_1.py — Basic Scramble
$
Input:
{"s1": "great", "s2": "rgeat"}
›
Output:
true
💡 Note:
We can scramble 'great' to get 'rgeat': Split 'great' into 'gr' + 'eat', swap to get 'eat' + 'gr' = 'eatgr', then scramble 'eat' to 'rge' and 'gr' to 'at', resulting in 'rgeat'.
example_2.py — No Valid Scramble
$
Input:
{"s1": "abcdef", "s2": "fecadb"}
›
Output:
false
💡 Note:
Although both strings have the same characters, there's no way to scramble 'abcdef' following the algorithm rules to get 'fecadb'.
example_3.py — Single Character
$
Input:
{"s1": "a", "s2": "a"}
›
Output:
true
💡 Note:
Single character strings are scrambled versions of themselves if they are identical.
Constraints
- 1 ≤ s1.length, s2.length ≤ 30
- s1 and s2 consist of lowercase English letters only
- Both strings have the same length
Visualization
Tap to expand
Understanding the Visualization
1
Start with Original
Begin with the original string 'great'
2
Choose Split Point
Split at any position, e.g., 'gr' | 'eat'
3
Decide Swap or Keep
Either keep as 'gr' + 'eat' or swap to 'eat' + 'gr'
4
Recurse on Parts
Apply the same process to each substring
5
Build Result
Combine results: 'rg' + 'eat' = 'rgeat'
Key Takeaway
🎯 Key Insight: At each level, we have two choices: keep the order of split parts or swap them. The optimal DP solution systematically checks all possibilities without redundant calculations.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code