#132

Palindrome Partitioning II

Hard
StringDynamic ProgrammingDynamic ProgrammingTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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 subproblems. We can create a table to keep track of whether substrings are palindromes and another array to store the minimum cuts needed for each position in the string.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a 2D array `isPalindrome` to track if substrings are palindromes.
  2. 2Step 2: Create a 1D array `cuts` to store the minimum cuts needed up to each index.
  3. 3Step 3: Fill the `isPalindrome` table by checking each substring.
  4. 4Step 4: For each character, calculate the minimum cuts needed using the `cuts` array.
solution.py19 lines
1# Full working Python code
2
3def min_cuts(s):
4    n = len(s)
5    if n == 0:
6        return 0
7    is_palindrome = [[False] * n for _ in range(n)]
8    cuts = [0] * n
9    for i in range(n):
10        min_cuts_needed = i
11        for j in range(i + 1):
12            if s[j] == s[i] and (i - j < 2 or is_palindrome[j + 1][i - 1]):
13                is_palindrome[j][i] = True
14                min_cuts_needed = 0 if j == 0 else min(min_cuts_needed, cuts[j - 1] + 1)
15        cuts[i] = min_cuts_needed
16    return cuts[-1]
17
18# Example usage
19print(min_cuts('aab'))

Complexity note: The time complexity is O(n²) due to the nested loops checking each substring for palindrome status. The space complexity is O(n²) because we maintain a 2D array to store palindrome checks.

  • 1Understanding palindromes is crucial for this problem.
  • 2Dynamic programming can optimize recursive solutions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.