#131
Palindrome Partitioning
MediumStringDynamic ProgrammingBacktrackingBacktrackingDynamic Programming
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 precompute a table that tells us if any substring is a palindrome. This allows us to efficiently build partitions without checking each substring multiple times.
⚙️
Algorithm
3 steps- 1Step 1: Create a 2D array to store palindrome information for substrings.
- 2Step 2: Fill the array using dynamic programming to mark palindromic substrings.
- 3Step 3: Use backtracking to generate partitions based on the precomputed palindrome information.
solution.py25 lines
1def partition(s):
2 n = len(s)
3 dp = [[False] * n for _ in range(n)]
4 for i in range(n):
5 dp[i][i] = True
6 for length in range(2, n + 1):
7 for start in range(n - length + 1):
8 end = start + length - 1
9 dp[start][end] = (s[start] == s[end]) and (length == 2 or dp[start + 1][end - 1])
10 result = []
11 backtrack(0, [], result, s, dp)
12 return result
13
14def backtrack(start, path, result, s, dp):
15 if start == len(s):
16 result.append(path[:])
17 return
18 for end in range(start + 1, len(s) + 1):
19 if dp[start][end - 1]:
20 path.append(s[start:end])
21 backtrack(end, path, result, s, dp)
22 path.pop()
23
24# Example usage:
25print(partition('aab'))ℹ
Complexity note: The time complexity is O(n²) due to filling the palindrome table and the backtracking process. The space complexity is O(n²) because of the 2D array used to store palindrome information.
- 1Understanding how to efficiently check for palindromes is crucial for optimizing the solution.
- 2Dynamic programming can significantly reduce the time complexity by avoiding redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.