Scramble String

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.

Example 1
Inputs1 = "great", s2 = "rgeat"
Outputtrue
Splitting great into gr and eat, then scrambling gr into rg, produces rgeat.
Example 2
Inputs1 = "abcde", s2 = "caebd"
Outputfalse
No sequence of valid recursive splits and swaps can transform abcde into caebd.

Constraints

  • s1.length == s2.length
  • 1 <= s1.length <= 30
  • s1 and s2 consist of lowercase English letters

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate