Scramble String — LeetCode 87 Python Solution

HardStringDynamic Programming
Problem
#87
Reading time
3 min

The problem

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.

Example

Input
s1 = "great", s2 = "rgeat"
Output
true
Explanation
One possible scenario applied on s1 is:

Python solution

Python
class Solution:
    def isScramble(self, s1: str, s2: str) -> bool:
        @cache
        def dfs(i: int, j: int, k: int) -> bool:
            if k == 1:
                return s1[i] == s2[j]
            for h in range(1, k):
                if dfs(i, j, h) and dfs(i + h, j + h, k - h):
                    return True
                if dfs(i + h, j, k - h) and dfs(i, j + k - h, h):
                    return True
            return False

        return dfs(0, 0, len(s1))

Complexity

MeasureComplexity
TimeO(n^4)
SpaceO(n^3) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 87. Scramble String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 87. Scramble String?
LeetCode 87. Scramble String is rated Hard on LeetCode.
What is the time complexity of LeetCode 87. Scramble String?
The Python solution on this page runs in O(n^4).
What is the space complexity of LeetCode 87. Scramble String?
The Python solution on this page uses O(n^3) auxiliary space.
What topics does LeetCode 87. Scramble String cover?
LeetCode 87. Scramble String is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview