Palindrome Partitioning II

Hard

Topics
StringDynamic Programming

Given a string s, partition it so that every substring of the partition is a palindrome. Return the minimum number of cuts needed for such a partitioning.

Example 1

aab
one piecethe next
The shading cuts the string into aa + b, and every piece reads the same backwards. The answer counts the cuts rather than the pieces, so 2 pieces means 1. A single character is always a palindrome, so some partition always exists — the question is only how few cuts it takes.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "aab"
Output: 1

Example 2

a
one piece
The shading cuts the string into a, and every piece reads the same backwards.
Input:  s = "a"
Output: 0

Example 3

ab
one piecethe next
Input:  s = "ab"
Output: 1

Constraints

  • 1 <= s.length <= 2000
  • s consists of lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Let cut[i] be the minimum cuts needed for the prefix ending at i. If s[j..i] is a palindrome, then the prefix can be cut as "best partition of s[0..j-1]" plus one more piece, costing cut[j-1] + 1 — and when j is 0 the whole prefix is one palindrome, needing zero cuts.

The palindrome test has to be O(1) or the whole thing is cubic. Build it into the same loop: s[j..i] is a palindrome when its ends match and its interior s[j+1..i-1] already is — which, with i growing outward, is always a shorter interval already computed. Lengths 1 and 2 need no interior check, which is the i - j < 2 clause.

Interleaving the two tables is the trick: a separate palindrome pre-pass works too, but doing both in one sweep is shorter and makes the dependency order obvious.

Approach

  1. Iterate i from left to right, seeding cut[i] at i, the worst case of cutting every character apart.
  2. For each j <= i, mark s[j..i] as a palindrome when the ends match and the interior is one.
  3. On a palindrome, relax cut[i] to 0 if j == 0, else to cut[j-1] + 1.
  4. Return cut[n-1].

Dry Run

s = "aab"

  i=0  palindromes ending here: ["a"]        j=0 reaches the start -> cut[0] = 0
  i=1  palindromes ending here: ["aa", "a"]  j=0 gives "aa"        -> cut[1] = 0
  i=2  palindromes ending here: ["b"]        j=2, so cut[1] + 1    -> cut[2] = 1

answer 1      the partition is "aa" | "b"

Complexity

  • Time — O(n²): every (j, i) pair is visited once with O(1) work. Measured: 0.47s for a 2,000-character all-same string, the worst case for palindrome density.
  • Space — O(n²) for the palindrome table. It can be reduced to O(n) by expanding around every centre instead, which computes the same information in the same time with a one-dimensional cut array — the natural follow-up when memory is raised.

Common Pitfalls

  • Testing each substring for palindromicity from scratch, which makes the solution O(n³) and is the single most common way this is failed.
  • Building the palindrome table in the wrong order. pal[j+1][i-1] must already be computed, which it is when the outer loop grows i and the inner scans j — reversing the loops breaks the dependency silently.
  • Omitting the i - j < 2 base case, which indexes an empty or inverted interior for lengths 1 and 2.
  • Seeding cut[i] at 0 instead of i. The worst case really is i cuts, and starting at 0 makes every prefix look free.
  • Returning the number of pieces rather than cuts. k pieces need k-1 cuts, and the off-by-one is easy to ship.
  • Running the recursive partition search with memoisation on the start index only. The state is fine, but without the precomputed palindrome table each state still costs O(n²) to explore.

Full Solution — all languages

class Solution:
    def minCut(self, s):
        n = len(s)
        if n <= 1:
            return 0
        pal = [[False] * n for _ in range(n)]
        cut = [0] * n
        for i in range(n):
            mn = i
            for j in range(i + 1):
                if s[j] == s[i] and (i - j < 2 or pal[j + 1][i - 1]):
                    pal[j][i] = True
                    mn = 0 if j == 0 else min(mn, cut[j - 1] + 1)
            cut[i] = mn
        return cut[n - 1]
SensAI
Beta
Tap the mic to stop voice mode