Palindrome Partitioning II solution explained
Palindrome Partitioning II asks for the fewest cuts that split a string into pieces that are all palindromes. Let cuts[i] be the fewest cuts for the first i characters, with cuts[0] = -1 so that a prefix which is itself a palindrome needs 0. Then cuts[j + 1] = min(cuts[i] + 1) over every palindrome s[i..j] ending at j. Finding those palindromes by expanding around each center keeps the whole solution at O(n²) time and O(n) extra memory.
By Evin JohnPublished 7 min read
The problem, restated
You get a string. Cut it into consecutive pieces so that each piece is a palindrome. A single character always counts as a palindrome, so a valid split always exists. Return the smallest number of cuts needed.
| String | Fewest cuts | One best split |
|---|---|---|
| racecar | 0 | racecar |
| noonabbad | 2 | noon | abba | d |
| banana | 1 | b | anana |
| abacd | 2 | aba | c | d |
| abcde | 4 | every letter alone |
What the interviewer is checking
This problem follows the first Palindrome Partitioning, which lists every split. The jump here is from enumerating to optimizing, and interviewers want to see that you do not reuse the backtracking. They look for a prefix DP with a clear meaning, a way to test "is s[i..j] a palindrome" in O(1) per check, and a complexity argument for O(n²). Bonus points for getting memory down to O(n) with center expansion.
Worth asking
- Cuts or pieces? Cuts, which is pieces minus one. That is why cuts[0] is -1.
- Is the empty string possible? If so, return 0, and guard for it: with cuts[0] = -1, the formula alone would return -1.
- Character set? It does not matter for the algorithm.
Brute force: try every set of cuts
A string of n letters has n - 1 gaps, and each gap is either cut or not, so there are 2^(n - 1) ways to split it. Checking each split means testing every piece for being a palindrome, which costs O(n) per split. That search is hopeless beyond about twenty letters, but it is the clearest statement of what is being minimized, and it is the reference this page's code was tested against. The waste is easy to see: the same suffix gets re-solved for every way of cutting the part before it.
Why greedy does not work
Taking the longest palindrome at the front and repeating sounds plausible. On "abaab", the longest palindromic prefix is "aba", which leaves "ab" and forces two more pieces: aba | a | b, 2 cuts. Cutting after the first letter instead gives a | baab, just 1 cut. The best first piece depends on what it leaves behind, which is the signal for DP.
Prefix DP with a palindrome table
First build pal[i][j], true when s[i..j] is a palindrome. Fill it with i going down from the end so that pal[i + 1][j - 1] is ready: s[i..j] is a palindrome when its ends match and its inside is one (or is empty or a single letter). Then cuts[j + 1] is the minimum of cuts[i] + 1 over every i with pal[i][j].
def min_cut_table(s):
if not s:
return 0
n = len(s)
pal = [[False] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i, n):
if s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1]):
pal[i][j] = True
cuts = [-1] + [0] * n
for j in range(n):
cuts[j + 1] = min(cuts[i] + 1 for i in range(j + 1) if pal[i][j])
return cuts[n]cuts[0] = -1 is the small trick that makes the formula uniform. If the whole prefix s[0..j] is a palindrome, then i = 0 qualifies and cuts[j + 1] = -1 + 1 = 0, which is right: no cut is needed.
Center expansion: O(n) memory
Every palindrome has a center, either a letter (odd length) or the gap between two letters (even length). Expanding outward from each of the 2n - 1 centers visits every palindromic substring exactly once. Each time you find that s[l..r] is a palindrome, update cuts[r + 1] with cuts[l] + 1. Start every cuts[i] at its worst value, i - 1, which is every letter on its own. Why is cuts[l] already final when it is read? It depends only on palindromes that end at l - 1, and each of those has its center at or before l - 1, which is earlier than the current center. Processing centers from left to right therefore settles cuts[l] before anything reads it.
def min_cut(s):
if not s:
return 0
n = len(s)
cuts = [i - 1 for i in range(n + 1)]
for center in range(n):
for left, right in ((center, center), (center, center + 1)):
while left >= 0 and right < n and s[left] == s[right]:
cuts[right + 1] = min(cuts[right + 1], cuts[left] + 1)
left -= 1
right += 1
return cuts[n]function minCut(s) {
if (s.length === 0) return 0;
const n = s.length;
const cuts = Array.from({ length: n + 1 }, (_, i) => i - 1);
for (let center = 0; center < n; center++) {
for (const [l0, r0] of [[center, center], [center, center + 1]]) {
let left = l0;
let right = r0;
while (left >= 0 && right < n && s[left] === s[right]) {
cuts[right + 1] = Math.min(cuts[right + 1], cuts[left] + 1);
left--;
right++;
}
}
}
return cuts[n];
}Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Try every set of cut positions | O(2^n × n) | O(n) |
| Prefix DP, palindrome checked by scanning | O(n³) | O(n) |
| Palindrome table plus prefix DP | O(n²) | O(n²) |
| Center expansion plus prefix DP | O(n²) | O(n) |
Edge cases
- A single character or an already palindromic string: 0.
- All distinct characters: n - 1 cuts.
- All the same character: 0, and the center expansion does the most work here.
- Even-length palindromes such as "abba", which need the gap centers.
Common mistakes
- Returning the number of pieces instead of cuts, which is off by one.
- Expanding only around letters and missing even-length palindromes.
- Filling the palindrome table with i going up, so pal[i + 1][j - 1] is read before it is set.
- Using the greedy longest-palindrome-first rule.
- Reusing the backtracking from the list-all-partitions version, which is exponential.
How to explain it out loud
Fictional example
- Candidate
- Let cuts of i be the fewest cuts for the first i characters. The last piece of an optimal split is some palindrome s[i..j], so cuts of j plus one is the best cuts of i plus one over those palindromes. I set cuts of 0 to minus one so a palindromic prefix costs zero.
- Candidate
- I need palindrome checks in constant time. I can precompute an n by n table, or expand around each of the 2n minus 1 centers and update cuts as I find palindromes, which keeps memory linear.
- Interviewer
- Why not take the longest palindrome first?
- Candidate
- On abaab, aba first leaves ab and costs two cuts, but a then baab costs one.
Related problems
Minimum Insertion Steps to Make a String Palindrome asks a different palindrome question with an interval DP. Shortest Common Supersequence builds a string from a DP table rather than counting. Word Break has the same prefix shape, where "is this piece a palindrome" becomes "is this piece in the dictionary", and Minimum Cost Tree From Leaf Values is another problem about where to split.
Practicing with Natively
Saying the meaning of cuts[i] and why it starts at -1 is the part to rehearse. In a mock interview on Mac or Windows, Natively transcribes the session so you can check whether your definition was clear before the code. After you have solved it yourself, Natively can read the problem from a screenshot and suggest an approach to compare with yours. Learn more about the AI interview assistant.
Questions people ask
How do you solve Palindrome Partitioning II?
Let cuts[i] be the fewest cuts for the first i characters, with cuts[0] = -1. For every palindrome s[i..j], cuts[j + 1] = min(cuts[j + 1], cuts[i] + 1). Find the palindromes by expanding around each center.
Why is cuts[0] set to -1?
So that a prefix which is itself a palindrome gets -1 + 1 = 0 cuts, keeping one formula for every case.
What is the time complexity of Palindrome Partitioning II?
O(n squared) time. A palindrome table uses O(n squared) memory; center expansion needs only O(n).
Does taking the longest palindrome first work?
No. On abaab, taking aba first leads to 2 cuts, while a | baab needs only 1.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
