Scramble String
Hard
Topics
We can scramble a string s by recursively splitting it into two non-empty substrings and optionally swapping them, then scrambling each part. Given two strings s (as s) and t, return true if t is a scrambled string of s.
Example 1
Input: s = "great", t = "rgeat" Output: true
Example 2
Input: s = "abcde", t = "caebd" Output: false
Example 3
Input: s = "a", t = "a" Output: true
Constraints
- s.length == t.length
- 1 <= s.length <= 8
- s and t consist of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
The scramble operation is recursive: split into two non-empty parts, optionally swap them, then scramble each part independently. So testing whether t is a scramble of s means trying every split point in both orientations and recursing.
Without memoisation that branches enormously. Two prunings tame it. First, memoise on the pair of substrings — the same pair recurs constantly across different split paths. Second, and more importantly, check that the two strings are anagrams before recursing: if their character counts differ, no sequence of splits and swaps can ever match them, and this single test kills the vast majority of the search tree.
The two orientations at split i are: no swap, comparing the first i of each and the rest of each; and swap, comparing the first i of s against the last i of t.
Approach
- Return true on equality and false on differing lengths.
- Return the memoised answer if this pair has been seen.
- Reject immediately when the character counts differ.
- For each split point, try the unswapped pairing and then the swapped one.
- Memoise and return.
Dry Run
"great" vs "rgeat"
split "great" at 2 -> "gr" + "eat"
swapped orientation: compare "gr" against the last 2 of "rgeat" = "at" -- no
unswapped: compare "gr" against "rg", and "eat" against "eat"
"gr" vs "rg": split at 1, swapped -> "g" vs "g" and "r" vs "r" -> true
"eat" vs "eat": equal -> true
answer true
"abcde" vs "caebd" -> false
the anagram check passes, so the search runs -- and every split failsComplexity
- Time — O(n⁴): the state is a pair of equal-length substrings, which is O(n³) distinct states (two start positions and a length), and each tries O(n) split points.
- Space — O(n³) memo entries. The shown code keys on the concatenated strings, which is equivalent but stores O(n) characters per key; indexing by
(i, j, length)is the tighter form. At the stated bound of 8 characters either is trivial.
Common Pitfalls
- Omitting the anagram pre-check. It is not an optimisation so much as the reason the search terminates in reasonable time; without it the branching is unconstrained.
- Sorting the two strings to test the anagram property. Correct, but O(n log n) per state where counting is O(n) — and at this state count the difference shows.
- Trying only the unswapped orientation, which answers "is
treachable without ever swapping", a strictly weaker question. - Getting the swapped indices wrong. At split
ithe swapped comparison pairss[:i]witht[n-i:]ands[i:]witht[:n-i]; mixing up which side takesiand which takesn-iis the usual bug. - Allowing a split at 0 or
n. The problem requires both parts non-empty, and a zero-width split recurses on the same pair forever. - Memoising only successes. Negative results are what the pruning depends on.
Full Solution — all languages
class Solution:
def isScramble(self, s, t):
memo = {}
def rec(a, b):
if a == b:
return True
if len(a) != len(b):
return False
key = a + '#' + b
if key in memo:
return memo[key]
cnt = {}
for c in a:
cnt[c] = cnt.get(c, 0) + 1
for c in b:
cnt[c] = cnt.get(c, 0) - 1
for v in cnt.values():
if v != 0:
memo[key] = False
return False
n = len(a)
for i in range(1, n):
if rec(a[:i], b[:i]) and rec(a[i:], b[i:]):
memo[key] = True
return True
if rec(a[:i], b[n - i:]) and rec(a[i:], b[:n - i]):
memo[key] = True
return True
memo[key] = False
return False
return rec(s, t)import java.util.*;
class Solution {
public boolean isScramble(String s, String t) {
memo = new HashMap<>();
return rec(s, t);
}
Map<String,Boolean> memo;
private boolean rec(String a, String b) {
if (a.equals(b)) return true;
if (a.length() != b.length()) return false;
String key = a + "#" + b;
if (memo.containsKey(key)) return memo.get(key);
int[] cnt = new int[26];
for (char c : a.toCharArray()) cnt[c - 'a']++;
for (char c : b.toCharArray()) cnt[c - 'a']--;
for (int x = 0; x < 26; x++) if (cnt[x] != 0) {
memo.put(key, false);
return false;
}
int n = a.length();
for (int i = 1; i < n; i++) {
if (rec(a.substring(0, i), b.substring(0, i)) && rec(a.substring(i), b.substring(i))) {
memo.put(key, true);
return true;
}
if (rec(a.substring(0, i), b.substring(n - i)) && rec(a.substring(i), b.substring(0, n - i))) {
memo.put(key, true);
return true;
}
}
memo.put(key, false);
return false;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isScramble(string s, string t) {
unordered_map<string,bool> memo;
function<bool(string,string)> rec = [&](string a, string b) -> bool {
if (a == b) return true;
if (a.size() != b.size()) return false;
string key = a + "#" + b;
if (memo.count(key)) return memo[key];
int cnt[26] = {0};
for (char c : a) cnt[c - 'a']++;
for (char c : b) cnt[c - 'a']--;
for (int x = 0; x < 26; x++) if (cnt[x] != 0) {
memo[key] = false;
return false;
}
int n = a.size();
for (int i = 1; i < n; i++) {
if (rec(a.substr(0, i), b.substr(0, i)) && rec(a.substr(i), b.substr(i))) {
memo[key] = true;
return true;
}
if (rec(a.substr(0, i), b.substr(n - i)) && rec(a.substr(i), b.substr(0, n - i))) {
memo[key] = true;
return true;
}
}
memo[key] = false;
return false;
};
return rec(s, t);
}
};/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/ var isScramble = function(s, t) {
const memo = {};
const rec = (a, b) => {
if (a === b) return true;
if (a.length !== b.length) return false;
const key = a + '#' + b;
if (memo[key] !== undefined) return memo[key];
const cnt = {};
for (const c of a) cnt[c] = (cnt[c] || 0) + 1;
for (const c of b) cnt[c] = (cnt[c] || 0) - 1;
for (const k in cnt) if (cnt[k] !== 0) {
memo[key] = false;
return false;
}
const n = a.length;
for (let i = 1; i < n; i++) {
if (rec(a.substring(0, i), b.substring(0, i)) && rec(a.substring(i), b.substring(i))) {
memo[key] = true;
return true;
}
if (rec(a.substring(0, i), b.substring(n - i)) && rec(a.substring(i), b.substring(0, n - i))) {
memo[key] = true;
return true;
}
}
memo[key] = false;
return false;
};
return rec(s, t);
};