LeetCode #132 Hard

Palindrome Partitioning II

Palindrome Partitioning II is LeetCode 132 (Hard). Cut the string s into pieces that are all palindromes, using as few cuts as possible, and return the number of cuts.

  • The answer counts cuts, which is one less than the number of pieces. A string that already reads the same backwards needs 0.
  • s can have 2,000 letters, so trying every way to cut it is out of reach. An O(n²) method is the target.
Constraints
  • 1 <= s.length <= 2000
  • s consists of lowercase English letters only.
dpstringpalindrome
Open on LeetCode ↗
02

Intuition

Answer a smaller question for every prefix: how few cuts does s[0..j] need? Call it cuts[j].

The best split of s[0..j] ends with some palindrome s[i..j], and the part before it, s[0..i-1], is itself split as cheaply as possible. So cuts[j] is the smallest cuts[i - 1] + 1 over all palindromes s[i..j], or 0 if the whole prefix is a palindrome.

  • Palindrome checks in the same loop: s[i..j] is a palindrome when its end letters match and s[i+1..j-1] is one. That inner piece ends at j - 1, a column already filled, so the check is a table lookup.
How to spot this pattern

"Minimum number of cuts" or "fewest pieces" with a rule on each piece is a prefix DP: the best answer for a prefix is the best answer for a shorter prefix plus one more piece.

03

Approach

Try it first

Before reading on, take "abaab" and ask: if the last piece is "baab", what is left to solve, and has that already been solved? Aim for O(n²) time.

1

Start each prefix at its worst case

For end j, set best = j. Cutting between every pair of neighbouring letters always works and uses exactly j cuts, so the real answer can only be lower.

2

Try every possible last piece

Loop i from 0 to j. The piece s[i..j] is a palindrome when s[i] == s[j] and the inside is short (under two letters apart) or already marked in pal[i + 1][j - 1]. Record the result in pal[i][j] for later columns.

3

Price a palindromic last piece

If i is 0, the whole prefix is one palindrome and needs no cut, so best becomes 0. Otherwise one cut goes just before i, and the part before it costs cuts[i - 1], already known because it is a shorter prefix.

4

Store the prefix answer

Set cuts[j] = best and move to the next j. After the last letter, cuts[n - 1] is the answer for the whole string.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def minCut(self, s: str) -> int:
▶3 n = len(s)
▶4 pal = [[False] * n for _ in range(n)]
▶5 cuts = [0] * n
▶6 for j in range(n):
▶7 best = j
▶8 for i in range(j + 1):
▶9 if s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1]):
▶10 pal[i][j] = True
▶11 best = 0 if i == 0 else min(best, cuts[i - 1] + 1)
▶12 cuts[j] = best
▶13 return cuts[n - 1]
string0a1a2bcutsbest0for 0..0"a" is all one palindrome → 0 cuts
i0
j0
best0
Prefix "a" starts at its worst case, 0 cuts (one between every pair of letters). The whole prefix reads the same backwards, so it is a single piece and needs no cut at all. Nothing can beat 0.
string0a1a2bcuts0best0for 0..0fewest cuts for "a" = 0
cuts[0]0
Every possible last piece of "a" has been priced, so 0 is final. Longer prefixes will read it whenever their last piece starts at index 1.
string0a1a2bcuts0best0for 0..1"aa" is all one palindrome → 0 cuts
i0
j1
best0
Prefix "aa" starts at its worst case, 1 cut (one between every pair of letters). The whole prefix reads the same backwards, so it is a single piece and needs no cut at all. Nothing can beat 0.
string0a1a2bcuts0best0for 0..10cuts before+ 1 =1this split"a" as last piece → 1 cut, best stays 0
i1
j1
best0
"a" is a palindrome. Putting one cut before it leaves "a", whose best is already known: 0. So this split costs 1, which does not beat 0.
string0a1a2bcuts00best0for 0..1fewest cuts for "aa" = 0
cuts[1]0
Every possible last piece of "aa" has been priced, so 0 is final. Longer prefixes will read it whenever their last piece starts at index 2.
string0a1a2bcuts00best2for 0..2"aab" is not a palindrome → skip
i0
j2
best2
Prefix "aab" starts at its worst case, 2 cuts (one between every pair of letters). The end letters of "aab" differ, so it cannot be the last piece.
string0a1a2bcuts00best2for 0..2"ab" is not a palindrome → skip
i1
j2
best2
The end letters of "ab" differ, so it cannot be the last piece.
string0a1a2bcuts00best1for 0..20cuts before+ 1 =1this split"b" as last piece → 1 cut, new best
i2
j2
best1
"b" is a palindrome. Putting one cut before it leaves "aa", whose best is already known: 0. So this split costs 1, lower than 2.
string0a1a2bcuts001best1for 0..2fewest cuts for "aab" = 1
cuts[2]1
Every possible last piece of "aab" has been priced, so 1 is final. Longer prefixes will read it whenever their last piece starts at index 3.
string0a1a2bcuts001best1for 0..2answer: 1 cut
return1
The last prefix is the whole string, so its count is the answer.
05

Common pitfalls

Cutting off the longest palindrome first

✗ Wrong
Repeatedly remove the longest palindrome at the front of what is left.
✓ Right
For each prefix, try every palindromic last piece and keep the cheapest.

Grabbing the longest piece can force bad cuts later. For "abaab" the greedy split is aba | a | b with 2 cuts, but a | baab needs only 1.

Reading cuts[i - 1] when i is 0

✗ Wrong
best = min(best, cuts[i - 1] + 1)
✓ Right
best = 0 if i == 0 else min(best, cuts[i - 1] + 1)

When the whole prefix is a palindrome there is nothing before it and no cut is needed. In Python cuts[-1] silently reads the last slot, so "aba" returns 1 instead of 0; in C++ or Java the index is out of range.

06

Edge cases

No two neighbouring letters can join, like "abc"

Only single letters are palindromes, so every prefix keeps its worst case and the answer is n − 1.

One letter

The prefix of length one is a palindrome with i = 0, so the answer is 0.

07

Complexity

Time
O(n²)
Space
O(n²)
The two loops visit each pair i ≤ j once and do constant work there. The palindrome table holds n² flags, about four million for the largest input; the cut array adds O(n).
08

Palindrome Partitioning II FAQ

Can the memory drop below O(n²)?

Yes. Skip the table and grow palindromes outward from every centre, both single letters and gaps between letters. Each palindrome s[l..r] found updates cuts[r] with cuts[l - 1] + 1, or 0 when l is 0. Time stays O(n²) and only the cut array is stored.

Why does plain recursion time out?

Trying every first piece and recursing on the rest without remembering results solves the same suffix again and again, which grows exponentially. Caching the answer for each start index fixes the repeats, which is the same idea as the cut array here, run from the other end.

What changes from Palindrome Partitioning (number 131)?

Palindrome Partitioning wants every valid split written out, and there can be 2ⁿ⁻¹ of them, so it is a backtracking problem capped at 16 letters. Here only a count is returned, and counts for short prefixes are reused by longer ones.