87. Scramble String
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks whether a string s2 can be formed by scrambling another string s1 of the same length. The scrambling process is defined recursively: a string can be split into two non-empty parts, x and y. Then, we can either keep the order as x + y or swap them to get y + x. This process is applied recursively to x and y until the substrings have length 1.
Solution
Scramble String in Python
from functools import lru_cache
from collections import Counter
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
n = len(s1)
if n != len(s2):
return False
# Use lru_cache for memoization. It's a decorator that caches function calls.
# The state for memoization is (i1, i2, length).
@lru_cache(None)
def dp(i1: int, i2: int, length: int) -> bool:
# Extract substrings for comparison
sub1 = s1[i1:i1+length]
sub2 = s2[i2:i2+length]
# Base case: if substrings are identical, they are scrambles of each other.
if sub1 == sub2:
return True
# Pruning: if substrings are not anagrams, they can't be scrambles.
# This is a critical optimization.
if Counter(sub1) != Counter(sub2):
return False
# Recursive step: iterate through all possible split points.
for k in range(1, length):
# Case 1: No swap.
# Check s1[i1..i1+k-1] with s2[i2..i2+k-1] AND s1[i1+k..] with s2[i2+k..]
if dp(i1, i2, k) and dp(i1 + k, i2 + k, length - k):
return True
# Case 2: Swap.
# Check s1[i1..i1+k-1] with s2[i2+length-k..] AND s1[i1+k..] with s2[i2..i2+length-k-1]
if dp(i1, i2 + length - k, k) and dp(i1 + k, i2, length - k):
return True
return False
return dp(0, 0, n)
Scramble String in Java
class Solution {
private String s1_global;
private String s2_global;
// Memoization table: 0 for uncomputed, 1 for true, -1 for false.
private int[][][] memo;
public boolean isScramble(String s1, String s2) {
int n = s1.length();
if (n != s2.length()) {
return false;
}
this.s1_global = s1;
this.s2_global = s2;
// Dimensions: [s1_start_index][s2_start_index][length]
this.memo = new int[n][n][n + 1];
return solve(0, 0, n);
}
private boolean solve(int i1, int i2, int len) {
// If result is already computed, return it.
if (memo[i1][i2][len] != 0) {
return memo[i1][i2][len] == 1;
}
// Base case: check if substrings are equal.
if (s1_global.substring(i1, i1 + len).equals(s2_global.substring(i2, i2 + len))) {
memo[i1][i2][len] = 1;
return true;
}
// Pruning: check if substrings are anagrams. This is a critical optimization.
int[] counts = new int[26];
for (int i = 0; i < len; i++) {
counts[s1_global.charAt(i1 + i) - 'a']++;
counts[s2_global.charAt(i2 + i) - 'a']--;
}
for (int count : counts) {
if (count != 0) {
memo[i1][i2][len] = -1;
return false;
}
}
// Recursive step: try all possible split points.
for (int k = 1; k < len; k++) {
// Case 1: No swap.
if (solve(i1, i2, k) && solve(i1 + k, i2 + k, len - k)) {
memo[i1][i2][len] = 1;
return true;
}
// Case 2: Swap.
if (solve(i1, i2 + len - k, k) && solve(i1 + k, i2, len - k)) {
memo[i1][i2][len] = 1;
return true;
}
}
// If no split works, they are not scrambles.
memo[i1][i2][len] = -1;
return false;
}
}
Scramble String in C++
class Solution {
private:
// Memoization table: 0 for uncomputed, 1 for true, -1 for false.
// Dimensions: [s1_start_index][s2_start_index][length]
int memo[30][30][31];
string s1_global, s2_global;
int n;
bool solve(int i1, int i2, int len) {
// If result is already computed, return it.
if (memo[i1][i2][len] != 0) {
return memo[i1][i2][len] == 1;
}
// Base case: check if substrings are equal.
if (s1_global.substr(i1, len) == s2_global.substr(i2, len)) {
memo[i1][i2][len] = 1;
return true;
}
// Pruning: check if substrings are anagrams. This is a critical optimization.
int counts[26] = {0};
for (int i = 0; i < len; ++i) {
counts[s1_global[i1 + i] - 'a']++;
counts[s2_global[i2 + i] - 'a']--;
}
for (int i = 0; i < 26; ++i) {
if (counts[i] != 0) {
memo[i1][i2][len] = -1;
return false;
}
}
// Recursive step: try all possible split points.
for (int k = 1; k < len; ++k) {
// Case 1: No swap.
// s1[i1..i1+k-1] with s2[i2..i2+k-1] AND s1[i1+k..i1+len-1] with s2[i2+k..i2+len-1]
if (solve(i1, i2, k) && solve(i1 + k, i2 + k, len - k)) {
memo[i1][i2][len] = 1;
return true;
}
// Case 2: Swap.
// s1[i1..i1+k-1] with s2[i2+len-k..i2+len-1] AND s1[i1+k..i1+len-1] with s2[i2..i2+len-k-1]
if (solve(i1, i2 + len - k, k) && solve(i1 + k, i2, len - k)) {
memo[i1][i2][len] = 1;
return true;
}
}
// If no split works, they are not scrambles.
memo[i1][i2][len] = -1;
return false;
}
public:
bool isScramble(string s1, string s2) {
n = s1.length();
if (n != s2.length()) {
return false;
}
this->s1_global = s1;
this->s2_global = s2;
memset(memo, 0, sizeof(memo));
return solve(0, 0, n);
}
};
Scramble String in TypeScript
function isScramble(s1: string, s2: string): boolean {
const n = s1.length;
if (n !== s2.length) {
return false;
}
// Memoization map: key = `${i1}-${i2}-${len}`, value = boolean result.
const memo = new Map<string, boolean>();
const solve = (i1: number, i2: number, len: number): boolean => {
const key = `${i1},${i2},${len}`;
if (memo.has(key)) {
return memo.get(key)!;
}
// Base case: check if substrings are equal.
const sub1 = s1.substring(i1, i1 + len);
const sub2 = s2.substring(i2, i2 + len);
if (sub1 === sub2) {
memo.set(key, true);
return true;
}
// Pruning: check if substrings are anagrams. This is a critical optimization.
const counts: number[] = new Array(26).fill(0);
const aCharCode = 'a'.charCodeAt(0);
for (let i = 0; i < len; i++) {
counts[s1.charCodeAt(i1 + i) - aCharCode]++;
counts[s2.charCodeAt(i2 + i) - aCharCode]--;
}
for (const count of counts) {
if (count !== 0) {
memo.set(key, false);
return false;
}
}
// Recursive step: try all possible split points.
for (let k = 1; k < len; k++) {
// Case 1: No swap.
if (solve(i1, i2, k) && solve(i1 + k, i2 + k, len - k)) {
memo.set(key, true);
return true;
}
// Case 2: Swap.
if (solve(i1, i2 + len - k, k) && solve(i1 + k, i2, len - k)) {
memo.set(key, true);
return true;
}
}
// If no split works, they are not scrambles.
memo.set(key, false);
return false;
};
return solve(0, 0, n);
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.