hardDynamic ProgrammingStringDynamic Programming

Palindrome Partitioning II

hardTime: O(n^2)Space: O(n^2)

Recognize the pattern

minimum cuts to partition string into palindromesall substrings checked for palindrometwo DP layers

Brute force idea

The naive version of Palindrome Partitioning II sounds like this: Try all possible partitions recursively. Each cut position is either used or not. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

Better approach

The real unlock in Palindrome Partitioning II comes when you notice this: Two DPs: (1) isPalin[i][j] = is s[i.j] a palindrome? (2) dp[i] = min cuts for s[0.i]. For each i, if isPalin[0][i], dp[i] = 0. Otherwise dp[i] = min(dp[j] + 1) for all j where isPalin[j+1][i]. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Palindrome Partitioning II is this: dp[i] asks: what's the minimum cuts for the first i+1 characters? If the tail s[j+1.i] is a palindrome, then dp[i] = dp[j] + 1 (one cut after position j). Take the minimum over all valid j. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

The trap in Palindrome Partitioning II usually looks like this: Not precomputing the palindrome table — checking if each substring is a palindrome inline makes the solution. Precomputing isPalin is essential for. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Dynamic Programming Pattern