#1745
Palindrome Partitioning IV
HardStringDynamic ProgrammingDynamic ProgrammingTwo Pointers
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²)
We can preprocess the string to find all palindromic substrings and then use this information to efficiently check for valid partitions. This reduces redundant checks.
⚙️
Algorithm
3 steps- 1Step 1: Create a 2D array to store whether substrings are palindromes.
- 2Step 2: Fill this array by checking all substrings in a single pass.
- 3Step 3: Use two nested loops to find valid split points and check the preprocessed palindrome array.
solution.py15 lines
1def checkPartition(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 if s[start] == s[end]:
10 dp[start][end] = (length == 2) or dp[start + 1][end - 1]
11 for i in range(1, n - 1):
12 for j in range(i + 1, n):
13 if dp[0][i - 1] and dp[i][j - 1] and dp[j][n - 1]:
14 return True
15 return Falseℹ
Complexity note: The complexity is O(n²) due to the preprocessing step where we fill the palindrome table, but this is more efficient than the brute force approach because we avoid redundant palindrome checks.
- 1Preprocessing palindromes can save time in checking splits.
- 2Using a 2D array to store palindrome checks avoids redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.