09. Palindrome Partitioning II
Given a string s, partition s such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of s.
How It Works & Algorithmic Design
Solves using 1D Dynamic Programming with Center Expansion Palindrome Pre-Check:
- Min Cut Table: Let
cuts[i]be the min cuts needed for substrings[0...i]. - Initialize:
cuts[i] = i(maximum cuts needed). - Center-Expansion Loop: For each center $i$ (both odd and even centers):
- Expand outward while
s[left] === s[right]:- If
left === 0,cuts[right] = 0(entire prefix is a palindrome). - Else,
cuts[right] = Math.min(cuts[right], cuts[left - 1] + 1).
- If
- Expand outward while
Why This Approach Works Best
Expanding from centers avoids creating $O(n^2)$ 2D boolean palindrome matrices, optimizing runtime to $O(n^2)$ time and $O(n)$ space.
Example Walkthrough
Input
s = "aab"
Target string.
Optimal Cuts
"aa" | "b" (1 cut).
Palindromic parts.
Output
1
1 cut.
Answer: Palindrome Partitioning II Center Expansion implementation
function minCut(s) {
const n = s.length;
const cuts = Array.from({ length: n }, (_, i) => i);
for (let center = 0; center < n; center++) {
expand(center, center);
expand(center, center + 1);
}
function expand(left, right) {
while (left >= 0 && right < n && s[left] === s[right]) {
cuts[right] = left === 0 ? 0 : Math.min(cuts[right], cuts[left - 1] + 1);
left--; right++;
}
}
return cuts[n - 1];
}Expand palindrome centers outwards and update 1D cut array dynamically.
Key Takeaways
Center expansion tests both odd-length (
i, i) and even-length (i, i+1) palindromes.Eliminates auxiliary 2D boolean palindrome memo tables.
Executes in $O(n^2)$ time and $O(n)$ space.