Scramble String - Problem

We can scramble a string s to get a string t using the following algorithm:

  1. If the length of the string is 1, stop.
  2. 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 to x and y where s = x + y.
    • Randomly decide to swap the two substrings or to keep them in the same order. i.e., after this step, s may become s = x + y or s = y + x.
    • Apply step 1 recursively on each of the two substrings x and y.

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
Scramble String - Optimal Solution INPUT s1 = "great" g r e a t s2 = "rgeat" r g e a t Scramble Tree Structure: great gr eat SWAP: gr --> rg g r Result: "rg" + "eat" = "rgeat" ALGORITHM STEPS 1 Base Cases s1==s2: true, sorted!=: false 2 Memoization Check Return cached result if exists 3 Try All Splits Split at each index i (1 to n-1) 4 Two Cases per Split No swap OR swap substrings Case Analysis at split i: No Swap: s1[0:i]==s2[0:i] AND s1[i:n]==s2[i:n] Swap: s1[0:i]==s2[n-i:n] AND s1[i:n]==s2[0:n-i] 3D DP Approach dp[len][i][j] = true if s1[i:i+len] scrambles to s2[j:j+len] Time: O(n^4), Space: O(n^3) FINAL RESULT Valid Scramble Path Found: "great" Split at index 2 "gr" "eat" SWAP "gr" --> "rg" "rg" + "eat" = "rgeat" Output: true s2 IS a scramble of s1 Verification: [OK] Same length: 5 == 5 [OK] Same chars: sorted equal [OK] Valid scramble path exists Key Insight: A string is a valid scramble if we can find a split point where either: 1) Both halves match without swap (x1==x2 AND y1==y2), OR 2) Halves match with swap (x1==y2 AND y1==x2). Use memoization to avoid recomputing overlapping subproblems. TutorialsPoint - Scramble String | Optimal DP with Memoization
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen