Palindrome Partitioning II - Problem

Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum number of cuts needed for a palindrome partitioning of s.

A palindrome is a string that reads the same backward as forward.

Input & Output

Example 1 — Basic Partition
$ Input: s = "aab"
Output: 1
💡 Note: The string can be partitioned as "aa|b". "aa" and "b" are both palindromes, requiring only 1 cut.
Example 2 — Already Palindrome
$ Input: s = "aba"
Output: 0
💡 Note: The entire string "aba" is already a palindrome, so no cuts are needed.
Example 3 — Multiple Cuts Needed
$ Input: s = "abcde"
Output: 4
💡 Note: Each character must be its own partition: "a|b|c|d|e", requiring 4 cuts.

Constraints

  • 1 ≤ s.length ≤ 2000
  • s consists of lowercase English letters only

Visualization

Tap to expand
Palindrome Partitioning II INPUT String s = "aab" 'a' idx 0 'a' idx 1 'b' idx 2 Goal: Find minimum cuts so each part is palindrome Possible Partitions: "a" | "a" | "b" (2 cuts) "aa" | "b" (1 cut) "aab" not palindrome ALGORITHM STEPS 1 Init cuts[] array cuts[i] = i (max cuts) 0 1 2 2 Expand from centers Check odd/even palindromes Center at idx 0: "a" palindrome Center at idx 0-1: "aa" palindrome 3 Update cuts[] cuts[j] = min(cuts[j], cuts[i-1]+1) Found "aa" at [0,1]: cuts[1] = min(1, 0) = 0 4 Return cuts[n-1] Final: cuts[2] = 1 FINAL RESULT Optimal Partition: "aa" palindrome CUT "b" palindrome Output: 1 OK - Verified! 1 cut = minimum cuts[] = [0, 0, 1] Return cuts[2] = 1 Key Insight: Expand Around Centers approach finds all palindromes in O(n^2) while updating minimum cuts. For each palindrome s[i..j] found, update: cuts[j] = min(cuts[j], (i==0 ? 0 : cuts[i-1]+1)) This avoids pre-computing all palindrome substrings, making it more space efficient than standard DP. TutorialsPoint - Palindrome Partitioning II | Optimized DP with Expand Around Centers
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
125.0K Views
Medium-High Frequency
~25 min Avg. Time
3.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen