Scramble String (LeetCode 87): Solution and Explanation
Decide whether s2 can be produced from s1 by recursively splitting it into two parts and optionally swapping them.
Intuition
Look at the very first split of s1 at index k. It makes a left piece of length k and a right piece of length n - k. After scrambling, the left piece sits either at the front of s2 (no swap) or at the back (swap).
So s2 is a scramble of s1 exactly when some k works in one of two pairings: the first k letters of each string match as scrambles and so do the rests, or the first k letters of s1 match the last k letters of s2 and the rests match.
Each check is the same question on shorter substrings, described by a start in s1, a start in s2 and a length. There are only O(n^3) such triples, so memoizing them turns an exponential search into a polynomial one.
Splits only rearrange letters, so two substrings with different letter counts can be rejected at once. This prune removes most branches in practice.
Approach: Memoized recursion with letter-count pruning
- Define
solve(i, j, length): iss2[j..j+length)a scramble ofs1[i..i+length)? - Return a memoized answer if there is one.
- If the two substrings are equal, return true.
- Count letters. If the counts differ, store false and return.
- For each k from 1 to length - 1, return true if
solve(i, j, k) && solve(i+k, j+k, length-k)(no swap) orsolve(i, j+length-k, k) && solve(i+k, j, length-k)(swap). - Store false if no split works. The answer is
solve(0, 0, n).
Step-by-step example
s1 = "great", s2 = "rgeat"
- solve("great", "rgeat"): not equal, same letters. Try splits.
- k = 1, no swap: "g" vs "r" has different letters, false.
- k = 1, swap: "g" vs "t" is false too.
- k = 2, no swap: "gr" vs "rg". Same letters; its k = 1 swap pairs "g" with "g" and "r" with "r", so true.
- Then "eat" vs "eat" is equal, true. Both halves match, so the answer is true.
Code: Python, Java, C++
1class Solution:
2 def isScramble(self, s1: str, s2: str) -> bool:
3 memo = {}
4
5 def solve(i, j, length):
6 key = (i, j, length)
7 if key in memo:
8 return memo[key]
9 if s1[i:i + length] == s2[j:j + length]:
10 return True
11 cnt = [0] * 26
12 for t in range(length):
13 cnt[ord(s1[i + t]) - 97] += 1
14 cnt[ord(s2[j + t]) - 97] -= 1
15 res = False
16 if all(c == 0 for c in cnt):
17 for k in range(1, length):
18 if solve(i, j, k) and solve(i + k, j + k, length - k):
19 res = True
20 break
21 if solve(i, j + length - k, k) and solve(i + k, j, length - k):
22 res = True
23 break
24 memo[key] = res
25 return res
26
27 return solve(0, 0, len(s1))1class Solution {
2 private String s1, s2;
3 private int n;
4 private int[] memo;
5
6 public boolean isScramble(String s1, String s2) {
7 this.s1 = s1;
8 this.s2 = s2;
9 n = s1.length();
10 memo = new int[n * n * (n + 1)];
11 return solve(0, 0, n);
12 }
13
14 private boolean solve(int i, int j, int len) {
15 int key = (i * n + j) * (n + 1) + len;
16 if (memo[key] != 0) {
17 return memo[key] == 1;
18 }
19 if (s1.regionMatches(i, s2, j, len)) {
20 return true;
21 }
22 int[] cnt = new int[26];
23 for (int t = 0; t < len; t++) {
24 cnt[s1.charAt(i + t) - 'a']++;
25 cnt[s2.charAt(j + t) - 'a']--;
26 }
27 boolean same = true;
28 for (int c : cnt) if (c != 0) same = false;
29 boolean res = false;
30 if (same) {
31 for (int k = 1; k < len; k++) {
32 if (solve(i, j, k) && solve(i + k, j + k, len - k)) {
33 res = true;
34 break;
35 }
36 if (solve(i, j + len - k, k) && solve(i + k, j, len - k)) {
37 res = true;
38 break;
39 }
40 }
41 }
42 memo[key] = res ? 1 : 2;
43 return res;
44 }
45}1class Solution {
2 string a, b;
3 int n;
4 vector<int> memo;
5
6 bool solve(int i, int j, int len) {
7 int key = (i * n + j) * (n + 1) + len;
8 if (memo[key] != 0) {
9 return memo[key] == 1;
10 }
11 if (a.compare(i, len, b, j, len) == 0) {
12 return true;
13 }
14 int cnt[26] = {0};
15 for (int t = 0; t < len; t++) {
16 cnt[a[i + t] - 'a']++;
17 cnt[b[j + t] - 'a']--;
18 }
19 bool same = true;
20 for (int c : cnt) if (c != 0) same = false;
21 bool res = false;
22 if (same) {
23 for (int k = 1; k < len; k++) {
24 if (solve(i, j, k) && solve(i + k, j + k, len - k)) {
25 res = true;
26 break;
27 }
28 if (solve(i, j + len - k, k) && solve(i + k, j, len - k)) {
29 res = true;
30 break;
31 }
32 }
33 }
34 memo[key] = res ? 1 : 2;
35 return res;
36 }
37
38public:
39 bool isScramble(string s1, string s2) {
40 a = s1;
41 b = s2;
42 n = s1.size();
43 memo.assign(n * n * (n + 1), 0);
44 return solve(0, 0, n);
45 }
46};Time and space complexity
O(n^4)
There are O(n^3) (i, j, length) states, and each tries up to length - 1 splits with O(1) work per split once its children are memoized. The letter count adds O(n) per state.
O(n^3)
The memo holds one entry per (i, j, length) state; the recursion depth is at most n.
Other approaches
Bottom-up 3D DP (time O(n^4), space O(n^3))
Fill dp[len][i][j] for len = 1..n using the same two split pairings. Same complexity, no recursion, but it computes every state even when pruning would skip it.
Plain recursion (time Exponential, space O(n))
Try every split and both pairings without memoization. Correct but exponential, it times out at length 30.
Common mistakes
- Pairing the wrong pieces in the swap case: s1's first k letters go with s2's last k letters, not s2's first k.
- Skipping the letter-count prune. Without it the memoized search still works but explores far more states.
- Memoizing on substrings instead of indices, which copies strings and costs more memory.
- Forgetting that equal substrings are trivially scrambles, which is the base case for length 1.
Frequently asked questions
Why is checking the first split enough?
Any scramble starts with some first split of the whole string. Trying every k with both pairings covers every possible first move, and the recursion covers every later move.
Is a reversed string always a scramble?
Yes. Split off one letter, swap, and repeat on the rest; that reverses the string.
Does matching letter counts guarantee a scramble?
No. "abcde" and "caebd" have the same letters but no split works, so counts are only a necessary condition.