Scramble String

Hard

Topics
StringDynamic Programming

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

g0r1e2a3t4
Input:  s = "great", t = "rgeat"
Output: true

Example 2

a0b1c2d3e4
Input:  s = "abcde", t = "caebd"
Output: false

Example 3

a0
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

  1. Return true on equality and false on differing lengths.
  2. Return the memoised answer if this pair has been seen.
  3. Reject immediately when the character counts differ.
  4. For each split point, try the unswapped pairing and then the swapped one.
  5. 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 fails

Complexity

  • 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 t reachable without ever swapping", a strictly weaker question.
  • Getting the swapped indices wrong. At split i the swapped comparison pairs s[:i] with t[n-i:] and s[i:] with t[:n-i]; mixing up which side takes i and which takes n-i is 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)
SensAI
Beta
Tap the mic to stop voice mode