Palindrome Partitioning II (LeetCode 132): Solution and Explanation

Hard
String
Dynamic Programming

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Initialize dp[i] = i, the worst case of cutting s[0..i] into single characters.
  2. Create an n × n boolean table isPalin, all false.
  3. For each end from 0 to n - 1, and each start from 0 to end, test whether s[start] == s[end] and either the span is at most three characters or isPalin[start+1][end-1] is true.
  4. If so, mark isPalin[start][end] = True.
  5. When start == 0, the whole prefix is a palindrome, so set dp[end] = 0. Otherwise set dp[end] = min(dp[end], dp[start-1] + 1).
  6. Return dp[n-1].

Step-by-step example

s = "aab"
  1. dp starts as [0, 1, 2].
  2. end = 0: "a" is a palindrome starting at 0, so dp[0] = 0.
  3. end = 1: start = 0 gives "aa", a palindrome starting at 0, so dp[1] = 0. start = 1 gives "a", which offers dp[0] + 1 = 1, not better.
  4. end = 2: "aab" and "ab" fail because the end characters differ. start = 2 gives "b", offering dp[1] + 1 = 1, so dp[2] = 1.
  5. 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]

Time and space complexity

Time

O(n²)

The double loop visits every (start, end) pair once and does constant work per pair thanks to the palindrome table.

Space

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 dp to zeros or infinity instead of dp[i] = i, which either hides missing transitions or breaks the min.
  • Forgetting the start == 0 case and computing dp[-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.