HardNo. 0087

Scramble String — LeetCode 87 Python Solution

Topics
String, Dynamic Programming
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

PythonSolution
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

Time
O(n4)
Space · auxiliary
O(n3)

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

Related problems
No.ProblemDifficulty
0091Decode WaysMedium
0097Interleaving StringMedium
0010Regular Expression MatchingHard
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard
0044Wildcard MatchingHard

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(n4).

What is the space complexity of LeetCode 87. Scramble String?

The Python solution on this page uses O(n3) 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.

Free to download. Check it runs on your machine, then pick a plan.