#87
Scramble String
HardStringDynamic ProgrammingDynamic ProgrammingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n³) |
| Space | O(1) | O(n³) |
💡
Intuition
Time O(n³)Space O(n³)
The optimal solution uses dynamic programming to store results of previously computed states, avoiding redundant calculations. This significantly reduces the time complexity by ensuring that each unique combination of substrings is only computed once.
⚙️
Algorithm
4 steps- 1Step 1: Create a 3D DP table where dp[i][j][k] indicates whether s1 from index i of length k is a scramble of s2 from index j of length k.
- 2Step 2: Initialize the DP table for substrings of length 1 (single characters).
- 3Step 3: Iterate through lengths from 2 to n, and for each length, check all possible splits.
- 4Step 4: Update the DP table based on whether the substrings can be scrambled by checking both swapping and non-swapping cases.
solution.py16 lines
1def isScramble(s1, s2):
2 n = len(s1)
3 if n != len(s2): return False
4 dp = [[[False] * (n + 1) for _ in range(n)] for _ in range(n)]
5 for i in range(n):
6 for j in range(n):
7 dp[i][j][1] = (s1[i] == s2[j])
8 for length in range(2, n + 1):
9 for i in range(n - length + 1):
10 for j in range(n - length + 1):
11 for split in range(1, length):
12 if (dp[i][j][split] and dp[i + split][j + split][length - split]) or
13 (dp[i][j + length - split][split] and dp[i + split][j][length - split]):
14 dp[i][j][length] = True
15 break
16 return dp[0][0][n]ℹ
Complexity note: The time complexity is O(n³) due to the three nested loops iterating over the length of the string and the possible splits. The space complexity is also O(n³) because of the 3D DP table used to store results.
- 1Dynamic programming can significantly reduce redundant calculations.
- 2Understanding the recursive nature of the problem is crucial for both brute force and optimal solutions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.