Magicsheet logo

Palindrome Partitioning II

Hard
25%
Updated 8/1/2025

Palindrome Partitioning II

What is this problem about?

The Palindrome Partitioning II problem asks for the minimum number of cuts needed to partition a string into all-palindrome substrings. Unlike Palindrome Partitioning I (which returns all partitions), this only needs the count of cuts. This hard coding problem uses two-layer DP: one for palindrome checking and one for minimum cuts. The string and dynamic programming interview pattern is the core.

Why is this asked in interviews?

Microsoft, Meta, Amazon, Google, and Bloomberg ask this because it tests DP optimization — moving from backtracking (all solutions) to optimization (minimum cuts). The key insight is that minCut[i] = minimum cuts for s[0..i] can be computed efficiently using palindrome precomputation.

Algorithmic pattern used

Two-layer DP. First, precompute isPalin[i][j]. Then compute cuts[i] = minimum cuts for s[0..i]. For each i: if s[0..i] is already a palindrome, cuts[i]=0. Otherwise, cuts[i] = min(cuts[j]+1) for all j where s[j+1..i] is a palindrome. Alternatively, expand from each center for palindrome checking and update cuts.

Example explanation

s="aab". isPalin: "a"✓,"a"✓,"aa"✓,"b"✓,"ab"✗,"aab"✗. cuts[0]=0 ("a" is palindrome). cuts[1]=0 ("aa" is palindrome). cuts[2]: "aab" not palindrome. Try cuts[1]+1=1 (since "b" at pos 2 is palindrome). cuts[2]=1.

Common mistakes candidates make

  • Using brute-force recursion instead of DP.
  • Not precomputing the palindrome table.
  • Off-by-one: cuts[i] for s[0..i] inclusive.
  • Initializing cuts to i (worst case), not n-1.

Interview preparation tip

Palindrome Partitioning II is a classic DP optimization problem. The minimum cuts DP recurrence — "if s[0..i] is a palindrome, cuts=0; else min over all valid j" — is the key. The palindrome precomputation with Manacher's algorithm gives O(n) precomputation for an overall O(n²) solution. Practice deriving minimum-cost partitioning DPs from first principles.

Similar Questions