Palindrome Partitioning II
Hard
Topics
Given a string s, partition it so that every substring of the partition is a palindrome. Return the minimum number of cuts needed for such a partitioning.
Example 1
aa + b, and every piece reads the same backwards. The answer counts the cuts rather than the pieces, so 2 pieces means 1. A single character is always a palindrome, so some partition always exists — the question is only how few cuts it takes.Input: s = "aab" Output: 1
Example 2
a, and every piece reads the same backwards.Input: s = "a" Output: 0
Example 3
Input: s = "ab" Output: 1
Constraints
- 1 <= s.length <= 2000
- s consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Let cut[i] be the minimum cuts needed for the prefix ending at i. If s[j..i] is a palindrome, then the prefix can be cut as "best partition of s[0..j-1]" plus one more piece, costing cut[j-1] + 1 — and when j is 0 the whole prefix is one palindrome, needing zero cuts.
The palindrome test has to be O(1) or the whole thing is cubic. Build it into the same loop: s[j..i] is a palindrome when its ends match and its interior s[j+1..i-1] already is — which, with i growing outward, is always a shorter interval already computed. Lengths 1 and 2 need no interior check, which is the i - j < 2 clause.
Interleaving the two tables is the trick: a separate palindrome pre-pass works too, but doing both in one sweep is shorter and makes the dependency order obvious.
Approach
- Iterate
ifrom left to right, seedingcut[i]ati, the worst case of cutting every character apart. - For each
j <= i, marks[j..i]as a palindrome when the ends match and the interior is one. - On a palindrome, relax
cut[i]to 0 ifj == 0, else tocut[j-1] + 1. - Return
cut[n-1].
Dry Run
s = "aab"
i=0 palindromes ending here: ["a"] j=0 reaches the start -> cut[0] = 0
i=1 palindromes ending here: ["aa", "a"] j=0 gives "aa" -> cut[1] = 0
i=2 palindromes ending here: ["b"] j=2, so cut[1] + 1 -> cut[2] = 1
answer 1 the partition is "aa" | "b"Complexity
- Time — O(n²): every
(j, i)pair is visited once with O(1) work. Measured: 0.47s for a 2,000-character all-same string, the worst case for palindrome density. - Space — O(n²) for the palindrome table. It can be reduced to O(n) by expanding around every centre instead, which computes the same information in the same time with a one-dimensional cut array — the natural follow-up when memory is raised.
Common Pitfalls
- Testing each substring for palindromicity from scratch, which makes the solution O(n³) and is the single most common way this is failed.
- Building the palindrome table in the wrong order.
pal[j+1][i-1]must already be computed, which it is when the outer loop growsiand the inner scansj— reversing the loops breaks the dependency silently. - Omitting the
i - j < 2base case, which indexes an empty or inverted interior for lengths 1 and 2. - Seeding
cut[i]at 0 instead ofi. The worst case really isicuts, and starting at 0 makes every prefix look free. - Returning the number of pieces rather than cuts.
kpieces needk-1cuts, and the off-by-one is easy to ship. - Running the recursive partition search with memoisation on the start index only. The state is fine, but without the precomputed palindrome table each state still costs O(n²) to explore.
Full Solution — all languages
class Solution:
def minCut(self, s):
n = len(s)
if n <= 1:
return 0
pal = [[False] * n for _ in range(n)]
cut = [0] * n
for i in range(n):
mn = i
for j in range(i + 1):
if s[j] == s[i] and (i - j < 2 or pal[j + 1][i - 1]):
pal[j][i] = True
mn = 0 if j == 0 else min(mn, cut[j - 1] + 1)
cut[i] = mn
return cut[n - 1]import java.util.*;
class Solution {
public int minCut(String s) {
int n = s.length();
if (n <= 1) return 0;
boolean[][] pal = new boolean[n][n];
int[] cut = new int[n];
for (int i = 0; i < n; i++) {
int mn = i;
for (int j = 0; j <= i; j++) {
if (s.charAt(j) == s.charAt(i) && (i - j < 2 || pal[j + 1][i - 1])) {
pal[j][i] = true;
mn = j == 0 ? 0 : Math.min(mn, cut[j - 1] + 1);
}
}
cut[i] = mn;
}
return cut[n - 1];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int minCut(string s) {
int n = s.size();
if (n <= 1) return 0;
vector<vector<bool>> pal(n, vector<bool>(n, false));
vector<int> cut(n, 0);
for (int i = 0; i < n; i++) {
int mn = i;
for (int j = 0; j <= i; j++) {
if (s[j] == s[i] && (i - j < 2 || pal[j + 1][i - 1])) {
pal[j][i] = true;
mn = j == 0 ? 0 : min(mn, cut[j - 1] + 1);
}
}
cut[i] = mn;
}
return cut[n - 1];
}
};/**
* @param {string} s
* @return {number}
*/ var minCut = function(s) {
const n = s.length;
if (n <= 1) return 0;
const pal = Array.from({length: n}, () => new Array(n).fill(false));
const cut = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
let mn = i;
for (let j = 0; j <= i; j++) {
if (s[j] === s[i] && (i - j < 2 || pal[j + 1][i - 1])) {
pal[j][i] = true;
mn = j === 0 ? 0 : Math.min(mn, cut[j - 1] + 1);
}
}
cut[i] = mn;
}
return cut[n - 1];
};