To scramble a string, pick any point to cut it into two non-empty parts, then either keep the parts in place or swap them. Then scramble each part the same way, and so on, until every part is a single letter.
You are given two strings s1 and s2 of equal length. Return true if some sequence of these cuts and swaps turns s1 into s2, and false otherwise.
Example 1
Input: s1 = "abc", s2 = "bca" Output: true Why: cut into "a" and "bc", then swap them
2 more examples and the constraints
Example 2
Input: s1 = "abcd", s2 = "bdac" Output: false Why: same letters, but no cut and swap pattern works
Example 3
Input: s1 = "z", s2 = "z" Output: true Why: a single letter is already done
Constraints
s1ands2have the same length, from 1 to 30- Both contain only lowercase English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(n⁴)
- Bottom-up DP by lengthO(n⁴)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 30 | Verdict |
|---|---|---|---|
| Recursion with a memo | O(n⁴) | Passes; follows the definition | |
| Bottom-up DP by length | O(n⁴) | Best; no recursion |
n = length of the strings. The memo version often prunes early with the letter check; the table always fills every cell.
Edge cases to test
- One letter. "z" and "z" are true; "z" and "y" are false.
- Equal strings. Always true: never swap.
- Different letters. If the letter counts differ, no swaps can help: false.
- Same letters, still false. "abcd" and "bdac" have the same letters but no valid sequence of cuts.
- Full length 30. Plain recursion times out here; the memo or the table keeps it under a million steps.
Common mistakes
- Checking only the kept pairing and forgetting the swapped one (or the reverse).
- Matching the swapped left part against the start of s2 instead of its last k letters.
- Recursing without a memo, which is exponential on false cases with repeated letters.
How to talk through it
- 1Clarify. Can a part be swapped at any level? Same length always? Lowercase only?
- 2Write the recursion. For each cut, the halves match kept or swapped; give both index formulas.
- 3Spot the repeats. A call is fixed by two starts and a length: n³ states, so memoize.
- 4Go bottom-up. Fill the table by length; each cell reads only shorter ones.
- 5Test out loud. Run "abc" vs "bca", a one-letter pair, and a pair with the same letters that fails.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?