Palindrome Partitioning II (LeetCode 132): Solution and Explanation
Split a string into pieces so that every piece reads the same forward and backward, using as few cuts as possible. Return that minimum number of cuts, which is the number of pieces minus one.
Watch it run step by step
Try your own input and write the code →Intuition
The first version of this problem asks for every palindrome partition, which is a backtracking job with exponential output. Here we only need the minimum count, and that changes the tool to dynamic programming. Think about the last piece of an optimal partition of s[0..end]. It is some palindrome s[start..end], and everything before it, s[0..start-1], must itself be partitioned optimally. So the best answer for a prefix ending at end is the minimum over all palindromic last pieces of one cut plus the best answer for the shorter prefix.
That recurrence alone is O(n²) transitions, but checking whether each s[start..end] is a palindrome naively costs O(n) more, giving O(n³). The second observation removes that factor: s[start..end] is a palindrome exactly when its end characters match and the inside s[start+1..end-1] is a palindrome. If we store those answers in a table isPalin, each check becomes O(1).
The reference solution fills both tables in a single double loop. It iterates end left to right and, for each, every start up to end. Whenever s[start..end] is a palindrome it either sets dp[end] = 0 (the whole prefix is one palindrome, no cut needed) or tries dp[start - 1] + 1. The inside entry isPalin[start+1][end-1] was filled during an earlier end, so the order of evaluation works out.
Approach: Two-table dynamic programming
- Initialize
dp[i] = i, the worst case of cuttings[0..i]into single characters. - Create an n × n boolean table
isPalin, all false. - For each
endfrom 0 to n - 1, and eachstartfrom 0 toend, test whethers[start] == s[end]and either the span is at most three characters orisPalin[start+1][end-1]is true. - If so, mark
isPalin[start][end] = True. - When
start == 0, the whole prefix is a palindrome, so setdp[end] = 0. Otherwise setdp[end] = min(dp[end], dp[start-1] + 1). - Return
dp[n-1].
Step-by-step example
s = "aab"
dpstarts as [0, 1, 2].- end = 0: "a" is a palindrome starting at 0, so
dp[0] = 0. - end = 1: start = 0 gives "aa", a palindrome starting at 0, so
dp[1] = 0. start = 1 gives "a", which offersdp[0] + 1 = 1, not better. - end = 2: "aab" and "ab" fail because the end characters differ. start = 2 gives "b", offering
dp[1] + 1 = 1, sodp[2] = 1. - Return
dp[2] = 1, matching the partition "aa" | "b".
Code: Python, Java, C++
1class Solution:
2 def minCut(self, s: str) -> int:
3 n = len(s)
4 # dp[i] = min cuts for s[0:i+1]
5 dp = list(range(n))
6
7 # isPalin[i][j] = True if s[i:j+1] is palindrome
8 isPalin = [[False] * n for _ in range(n)]
9
10 for end in range(n):
11 for start in range(end + 1):
12 if s[start] == s[end] and (end - start <= 2 or isPalin[start+1][end-1]):
13 isPalin[start][end] = True
14 if start == 0:
15 dp[end] = 0
16 else:
17 dp[end] = min(dp[end], dp[start-1] + 1)
18
19 return dp[n-1]1class Solution {
2 public int minCut(String s) {
3 int n = s.length();
4 int[] dp = new int[n];
5 boolean[][] isPalin = new boolean[n][n];
6
7 for (int i = 0; i < n; i++) dp[i] = i;
8
9 for (int end = 0; end < n; end++) {
10 for (int start = 0; start <= end; start++) {
11 if (s.charAt(start) == s.charAt(end) &&
12 (end - start <= 2 || isPalin[start + 1][end - 1])) {
13 isPalin[start][end] = true;
14 if (start == 0) {
15 dp[end] = 0;
16 } else {
17 dp[end] = Math.min(dp[end], dp[start - 1] + 1);
18 }
19 }
20 }
21 }
22
23 return dp[n - 1];
24 }
25}1class Solution {
2public:
3 int minCut(string s) {
4 int n = s.size();
5 vector<int> dp(n);
6 vector<vector<bool>> isPalin(n, vector<bool>(n, false));
7
8 for (int i = 0; i < n; i++) dp[i] = i;
9
10 for (int end = 0; end < n; end++) {
11 for (int start = 0; start <= end; start++) {
12 if (s[start] == s[end] &&
13 (end - start <= 2 || isPalin[start + 1][end - 1])) {
14 isPalin[start][end] = true;
15 if (start == 0) {
16 dp[end] = 0;
17 } else {
18 dp[end] = min(dp[end], dp[start - 1] + 1);
19 }
20 }
21 }
22 }
23
24 return dp[n - 1];
25 }
26};Time and space complexity
O(n²)
The double loop visits every (start, end) pair once and does constant work per pair thanks to the palindrome table.
O(n²)
The isPalin table has n × n entries. The dp array adds only O(n).
Other approaches
Expand around centers (time O(n²), space O(n))
For every center, expand outward while the characters match; each time the palindrome s[l..r] is found, update dp[r] from dp[l-1] + 1. It produces the same transitions without storing the palindrome table, so memory drops to linear.
Backtracking over all partitions (time O(n × 2^n), space O(n))
Enumerate every palindrome partition and keep the fewest pieces. It is the natural extension of the first partitioning problem but is exponential and times out on long inputs.
Common mistakes
- Initializing
dpto zeros or infinity instead ofdp[i] = i, which either hides missing transitions or breaks the min. - Forgetting the
start == 0case and computingdp[-1] + 1, which in Python silently reads the last element. - Checking the inside palindrome without the short span guard, which reads
isPalin[start+1][end-1]with crossed indices for spans of length one or two. - Returning the number of pieces instead of the number of cuts, which is off by one.
Frequently asked questions
Why is the time complexity O(n²) and not O(n³)?
Checking a substring naively would cost O(n), but the table lets us decide each s[start..end] from its inner substring in O(1). With n² pairs and constant work each, the total is quadratic.
How is this different from Palindrome Partitioning I?
The first problem wants every valid partition, so the output can be exponential and backtracking is required. This version only needs the minimum cut count, which collapses into a polynomial DP.
Can Palindrome Partitioning II use O(n) space?
Yes. Expanding around each of the 2n - 1 centers discovers every palindrome in order and updates the cut array directly, so the n × n table is not needed.