We can scramble a string s to get a string t using the following algorithm:
If the length of the string is 1, stop.
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:
Input: s1 = "great", s2 = "rgeat"
Output: true
Explanation: One possible scenario applied on s1 is:
"great" --> "gr/eat" // divide at random index.
"gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order.
"gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at random index each of them.
"g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order.
"r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t".
"r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order.
The algorithm stops now, and the result string is "rgeat" which is s2.
As one possible scenario led s1 to be scrambled to s2, we return true.
Problem summary: We can scramble a string s to get a string t using the following algorithm: If the length of the string is 1, stop. 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.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"great"
"rgeat"
Example 2
"abcde"
"caebd"
Example 3
"a"
"a"
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
import java.util.*;
class Solution {
private final Map<String, Boolean> memo = new HashMap<>();
public boolean isScramble(String s1, String s2) {
return dfs(s1, s2);
}
private boolean dfs(String a, String b) {
String key = a + "|" + b;
if (memo.containsKey(key)) return memo.get(key);
if (a.equals(b)) return true;
if (!sameCharMultiset(a, b)) {
memo.put(key, false);
return false;
}
int n = a.length();
for (int i = 1; i < n; i++) {
if (dfs(a.substring(0, i), b.substring(0, i))
&& dfs(a.substring(i), b.substring(i))) {
memo.put(key, true);
return true;
}
if (dfs(a.substring(0, i), b.substring(n - i))
&& dfs(a.substring(i), b.substring(0, n - i))) {
memo.put(key, true);
return true;
}
}
memo.put(key, false);
return false;
}
private boolean sameCharMultiset(String a, String b) {
if (a.length() != b.length()) return false;
int[] count = new int[26];
for (int i = 0; i < a.length(); i++) {
count[a.charAt(i) - 'a']++;
count[b.charAt(i) - 'a']--;
}
for (int x : count) if (x != 0) return false;
return true;
}
}
func isScramble(s1 string, s2 string) bool {
memo := map[string]bool{}
seen := map[string]bool{}
var sameChars func(a, b string) bool
sameChars = func(a, b string) bool {
if len(a) != len(b) {
return false
}
cnt := [26]int{}
for i := 0; i < len(a); i++ {
cnt[a[i]-'a']++
cnt[b[i]-'a']--
}
for _, v := range cnt {
if v != 0 {
return false
}
}
return true
}
var dfs func(a, b string) bool
dfs = func(a, b string) bool {
key := a + "|" + b
if seen[key] {
return memo[key]
}
seen[key] = true
if a == b {
memo[key] = true
return true
}
if !sameChars(a, b) {
memo[key] = false
return false
}
n := len(a)
for i := 1; i < n; i++ {
if dfs(a[:i], b[:i]) && dfs(a[i:], b[i:]) {
memo[key] = true
return true
}
if dfs(a[:i], b[n-i:]) && dfs(a[i:], b[:n-i]) {
memo[key] = true
return true
}
}
memo[key] = false
return false
}
return dfs(s1, s2)
}
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
memo = {}
def same_chars(a: str, b: str) -> bool:
if len(a) != len(b):
return False
cnt = [0] * 26
for x, y in zip(a, b):
cnt[ord(x) - 97] += 1
cnt[ord(y) - 97] -= 1
return all(v == 0 for v in cnt)
def dfs(a: str, b: str) -> bool:
key = (a, b)
if key in memo:
return memo[key]
if a == b:
memo[key] = True
return True
if not same_chars(a, b):
memo[key] = False
return False
n = len(a)
for i in range(1, n):
if dfs(a[:i], b[:i]) and dfs(a[i:], b[i:]):
memo[key] = True
return True
if dfs(a[:i], b[n - i:]) and dfs(a[i:], b[:n - i]):
memo[key] = True
return True
memo[key] = False
return False
return dfs(s1, s2)
use std::collections::HashMap;
impl Solution {
pub fn is_scramble(s1: String, s2: String) -> bool {
fn same_chars(a: &str, b: &str) -> bool {
if a.len() != b.len() {
return false;
}
let mut cnt = [0i32; 26];
let ba = a.as_bytes();
let bb = b.as_bytes();
for i in 0..ba.len() {
cnt[(ba[i] - b'a') as usize] += 1;
cnt[(bb[i] - b'a') as usize] -= 1;
}
cnt.iter().all(|&x| x == 0)
}
fn dfs(a: &str, b: &str, memo: &mut HashMap<String, bool>) -> bool {
let key = format!("{}|{}", a, b);
if let Some(&v) = memo.get(&key) {
return v;
}
if a == b {
memo.insert(key, true);
return true;
}
if !same_chars(a, b) {
memo.insert(key, false);
return false;
}
let n = a.len();
for i in 1..n {
if (dfs(&a[..i], &b[..i], memo) && dfs(&a[i..], &b[i..], memo))
|| (dfs(&a[..i], &b[n - i..], memo) && dfs(&a[i..], &b[..n - i], memo))
{
memo.insert(key, true);
return true;
}
}
memo.insert(key, false);
false
}
let mut memo = HashMap::new();
dfs(&s1, &s2, &mut memo)
}
}
function isScramble(s1: string, s2: string): boolean {
const memo = new Map<string, boolean>();
const sameChars = (a: string, b: string): boolean => {
if (a.length !== b.length) return false;
const cnt = Array(26).fill(0);
for (let i = 0; i < a.length; i++) {
cnt[a.charCodeAt(i) - 97]++;
cnt[b.charCodeAt(i) - 97]--;
}
return cnt.every((x) => x === 0);
};
const dfs = (a: string, b: string): boolean => {
const key = a + '|' + b;
if (memo.has(key)) return memo.get(key)!;
if (a === b) {
memo.set(key, true);
return true;
}
if (!sameChars(a, b)) {
memo.set(key, false);
return false;
}
const n = a.length;
for (let i = 1; i < n; i++) {
if ((dfs(a.slice(0, i), b.slice(0, i)) && dfs(a.slice(i), b.slice(i))) ||
(dfs(a.slice(0, i), b.slice(n - i)) && dfs(a.slice(i), b.slice(0, n - i)))) {
memo.set(key, true);
return true;
}
}
memo.set(key, false);
return false;
};
return dfs(s1, s2);
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n^4)
Space
O(n^3)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.