DSA Factory
Free Dynamic programming lessonsDynamic programming · Stage 7 · Intervals · Step 2

A helper table, then a smaller decision

Pre-compute which ranges are palindromes, then decide the fewest cuts using that lookup. About 13 minutes.

First, know which pieces are palindromes

You want to cut a word into pieces that each read the same backwards, using as few cuts as possible. "aab" needs one cut: "aa" and "b".

Start by answering a simpler question for every piece of the word: is it a palindrome? A single letter always is. A longer piece is a palindrome when its two end letters match and the piece between them is a palindrome too. That's a question about a shorter piece, so work from short pieces to long ones.

Ends match, middle is a palindrome: then the whole piece is one.

Then, the fewest cuts so far

Now walk along the word. For each position, ask: what's the fewest cuts that turns everything up to here into palindromes?

If everything up to here is already a palindrome, that's 0 cuts. Otherwise, try every place the last piece could start. If that last piece is a palindrome, it costs one cut plus the fewest cuts for everything before it. Keep the smallest.

Try every last piece: one cut plus the best before it.
In code
cuts = [0] * len(s)
cuts[end] = 0     # a whole palindrome
"aab" · top: is the piece from i to j a palindrome? · bottom: fewest cuts so far
j = 0j = 1j = 2
i = 0
✓
i = 1
✓
i = 2
✓
cuts

Every single letter is a palindrome.

Move 1 of 5
Quick check

In "aab", the pieces "a", "a", "b" and "aa" are palindromes, but "aab" isn't. What's the fewest cuts for the whole word?

  1. A1
  2. B0
  3. C2
Show the answer

1. Cut after "aa": "aa" and "b" are both palindromes.

Your problem

Minimum cuts for a palindrome partition

Given a string s, return the fewest cuts needed to split it into pieces that are each a palindrome. A string with no cuts needs 0 if it's already a palindrome.

Example
s = "aab" → 1

0 ≤ s.length ≤ 1,000 · lowercase English letters

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve