Scramble String solution explained

Scramble String asks whether a string t can be produced from a string s by cutting s into two non-empty pieces, scrambling each piece the same way, and joining the pieces in either order. Solve it with interval DP: t[j..j+len) is a scramble of s[i..i+len) when some cut point k makes both pieces match, either in the same order or swapped. Memoize on (i, j, len) and prune with a letter-count check, for O(n⁴) work in the worst case.

By Published 8 min read

The problem, in plain terms

Define a scramble of a string like this. A single character can only scramble to itself. A longer string can be cut at any point into a non-empty left piece and a non-empty right piece; each piece is then scrambled by the same rule, independently, and the two results are joined either in their original order or swapped. Given two strings s and t, decide whether t is one of the scrambles of s.

s = plane
cut into pl | ane, swap the pieces       -> ane + pl
scramble ane: cut a | ne, swap            -> nea
scramble pl:  cut p | l, swap             -> lp
result: nealp      (so nealp is a scramble of plane)

s = tame
reachable: meta, mate, team, and 19 other orderings
not reachable: aetm and mtea
Examples, made up for this page

The last two lines are the important ones. Every scramble is a rearrangement of the same letters, but the reverse is false, so a letter-count check alone cannot be the answer. Ask the interviewer whether the strings always have equal length and whether characters can repeat; repeats make the brute force produce duplicates but do not change the method.

Why it is an interview favorite

The definition is recursive, so the first solution almost writes itself, and it is exponential. The question is whether you can see the overlapping subproblems hiding in the recursion, choose a compact way to name them, and add cheap pruning. It is also a good test of off-by-one discipline, because the swapped case lines up pieces from opposite ends.

Brute force

The most literal approach generates every scramble of s and checks whether t is among them. For strings of 4, 5 and 6 distinct letters our generator produced 22, 90 and 394 different scrambles out of 24, 120 and 720 orderings, so the set grows quickly, and the generation repeats a lot of work for each cut. A slightly better brute force recurses directly on pairs of substrings without remembering answers; it is still exponential because the same pair of windows is solved again and again from different cuts.

The optimal approach: memoized interval DP

Pattern: interval dynamic programming on two strings. A subproblem asks whether the window of t that starts at j is a scramble of the window of s that starts at i, both of length len. If the windows are equal, the answer is yes. If they do not contain the same letters, the answer is no. Otherwise try every cut size k from 1 to len - 1. Kept order: the first k letters of each window match and the remaining letters match. Swapped order: the first k letters of the s window match the last k letters of the t window, and the rest of the s window matches the start of the t window. Any cut that works in either order makes the answer yes.

from functools import lru_cache


def is_scramble(s, t):
    if len(s) != len(t):
        return False

    @lru_cache(maxsize=None)
    def match(i, j, size):
        # can t[j:j+size] be produced by scrambling s[i:i+size]?
        a, b = s[i:i + size], t[j:j + size]
        if a == b:
            return True
        if sorted(a) != sorted(b):      # different letters: impossible
            return False
        for k in range(1, size):        # size of s's left piece
            if match(i, j, k) and match(i + k, j + k, size - k):
                return True             # pieces kept in order
            if match(i, j + size - k, k) and match(i + k, j, size - k):
                return True             # pieces swapped
        return False

    return match(0, 0, len(s))
Python: memoize on (i, j, size) with a letter check as pruning. Matched the generate-everything brute force on about 3,000 pairs.

Using indexes instead of passing substrings as the cache key keeps the key small and makes the state count obvious: n choices for i, n for j and n for size. The sorted comparison is the pruning step. It rejects most impossible windows immediately, which is why the memoized version is fast in practice even though its worst-case bound is high.

Bottom-up table in JavaScript

The same recurrence can fill a three-dimensional table by increasing length: windows of length 1 compare single characters, and every longer window only reads shorter ones. This version has no letter-count pruning, so it always does the full O(n⁴) work, but it has no recursion and its running time does not depend on the input.

function isScramble(s, t) {
  const n = s.length;
  if (t.length !== n) return false;
  // ok[len][i][j]: t.substr(j, len) is a scramble of s.substr(i, len)
  const ok = [];
  for (let len = 0; len <= n; len++) {
    ok.push(Array.from({ length: n }, () => new Array(n).fill(false)));
  }
  for (let i = 0; i < n; i++)
    for (let j = 0; j < n; j++) ok[1][i][j] = s[i] === t[j];
  for (let len = 2; len <= n; len++) {
    for (let i = 0; i + len <= n; i++) {
      for (let j = 0; j + len <= n; j++) {
        for (let k = 1; k < len && !ok[len][i][j]; k++) {
          ok[len][i][j] =
            (ok[k][i][j] && ok[len - k][i + k][j + k]) ||
            (ok[k][i][j + len - k] && ok[len - k][i + k][j]);
        }
      }
    }
  }
  return n === 0 || ok[n][0][0];
}
JavaScript: ok[len][i][j] filled by length. Ran with node on the same pairs plus longer ones and agreed with Python.

The inner loop stops at the first cut that works. Memory is O(n³) booleans, which is the main reason to prefer the top-down version when the strings are long and the pruning helps.

Complexity summary

n is the length of the strings
ApproachTimeExtra space
Generate every scramble of sExponentialExponential, for the set
Plain recursion on window pairsExponentialO(n) stack
Memoized, sort as pruningO(n⁴ log n) worst case, usually far lessO(n³) cache
Memoized, 26-letter counts as pruningO(n⁴) worst caseO(n³) cache
Bottom-up tableO(n⁴) alwaysO(n³)
n is the length of the strings. Scroll sideways on a small screen.

There are O(n³) window pairs and each tries O(n) cuts, which gives the n⁴ term. Sorting each window adds a log factor to the Python version as written; replacing the sort with a fixed-size letter count removes it.

A note on which orderings are reachable

For four distinct letters, the two unreachable orderings follow the patterns 2-4-1-3 and 3-1-4-2 in terms of original positions: tame to aetm is the first, tame to mtea the second. Orderings that avoid those two patterns are known in combinatorics as separable permutations, and the counts our brute force printed (1, 2, 6, 22, 90, 394 for one to six letters) match that sequence. You do not need this in an interview, but it explains why a quick test like checking letters or reversals never settles the question.

Edge cases to test

  • Different lengths: return false before doing anything else.
  • Identical strings, including a single character: true at once.
  • Same letters in an unreachable order, such as tame and aetm.
  • Repeated letters, like aabb against abab, where many cuts look plausible.
  • Both empty strings, if the interviewer allows them; both versions above return true.

Common mistakes

  • Returning true whenever the letters match, which the tame example disproves.
  • Lining up the swapped case wrong: the left piece of s must match the right end of the t window, starting at j + len - k.
  • Allowing a cut of size 0 or len, which recurses on the same problem forever.
  • Using whole substrings as memo keys in a language where that copies the strings on every lookup.
  • Forgetting that the two pieces are scrambled independently; only checking the swap at the top level misses deeper rearrangements.

How to explain it out loud

Fictional example

From the definition to a three-number state
Candidate
The definition is recursive, so I'll mirror it: for some cut, either the left pieces match and the right pieces match, or s's left piece matches t's right piece and the other way round.
Candidate
The recursion keeps asking about a window of s against a window of t of the same size, so I can name a subproblem by the two start positions and the size, and cache it. That's n cubed states with n cuts each.
Candidate
Before trying cuts I'll check the two windows have the same letters, which kills most branches early. Same letters isn't sufficient though, so the cut search is still needed.

A counting DP over a single string, where each step consumes one or two characters, is Decode Ways II. For a different kind of splitting question, asking whether a word is made of other words from a list, see Concatenated Words. A DP that tracks two moving positions at once, on a grid, is Cherry Pickup.

Natively as a practice partner

Interval DP is easier to say than to index, so practice both halves. On a Mac or Windows computer, Natively can read a problem like this from a screenshot during practice and write an approach and code, which gives you a reference for the swapped-case indexes when yours disagree. Reviewing the transcript afterward shows whether you named the state before writing the recursion. See the AI interview assistant.

Questions people ask

How do you solve Scramble String?

Use interval DP. A window of t is a scramble of an equal-length window of s if, for some cut, both pieces match in the same order or in swapped order. Memoize on the two start positions and the length, and skip windows whose letters differ.

Is having the same letters enough for Scramble String?

No. Every scramble uses the same letters, but not every rearrangement is a scramble. From four distinct letters, two of the 24 orderings cannot be reached, for example tame cannot become aetm.

What is the time complexity of Scramble String?

There are O(n³) window pairs and each tries O(n) cuts, so O(n⁴) in the worst case with O(n³) memory. Letter-count pruning makes typical inputs much faster.

How do you handle the swapped case in Scramble String?

For a cut of size k, compare the first k letters of the s window with the last k letters of the t window, and the remaining letters of s with the first part of t.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP