Scramble String - Problem
We can scramble a string s to get a string t using the following algorithm:
- If the length of the string is 1, stop.
- If the length of the string is > 1, do the following:
- Split the string into two non-empty substrings at a random index, i.e., if the string is
s, divide it toxandywheres = x + y. - Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step,
smay becomes = x + yors = y + x. - Apply step 1 recursively on each of the two substrings
xandy.
- Split the string into two non-empty substrings at a random index, i.e., if the string is
Given two strings s1 and s2 of the same length, return true if s2 is a scrambled string of s1, otherwise, return false.
Input & Output
Example 1 — Basic Scramble
$
Input:
s1 = "great", s2 = "rgeat"
›
Output:
true
💡 Note:
"great" can be scrambled to "rgeat" by splitting at position 2: "gr|eat" → swap to "eat|gr" → further scramble "eat" to "rge" → result "rgeat"
Example 2 — Not a Scramble
$
Input:
s1 = "abcde", s2 = "caebd"
›
Output:
false
💡 Note:
No valid scrambling sequence can transform "abcde" into "caebd" following the scramble rules
Example 3 — Identical Strings
$
Input:
s1 = "a", s2 = "a"
›
Output:
true
💡 Note:
Single character strings that are identical are always scrambles of each other
Constraints
- 1 ≤ s1.length, s2.length ≤ 30
- s1 and s2 consist of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two strings s1 and s2 of same length
2
Process
Check if s2 can be obtained by scrambling s1
3
Output
Return true if scramble is possible, false otherwise
Key Takeaway
🎯 Key Insight: A string is a scramble if it can be split where parts match in original or swapped order recursively
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code