hardDynamic ProgrammingStringDynamic Programming

Palindrome Partitioning II

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

Signals to notice

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

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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