Palindrome Partitioning II - Problem
Given a string s, your task is to partition the string into substrings such that every substring in the partition is a palindrome. A palindrome reads the same forwards and backwards (like "aba" or "racecar").
The goal is to find the minimum number of cuts needed to achieve such a palindrome partitioning. For example, if s = "aab", you could partition it as ["aa", "b"] with just 1 cut, since both "aa" and "b" are palindromes.
Key Points:
- Each partition must contain only palindromic substrings
- We want to minimize the total number of cuts
- A single character is always a palindrome
- The entire string might already be a palindrome (0 cuts needed)
Input & Output
example_1.py — Basic Case
$
Input:
s = "aab"
›
Output:
1
💡 Note:
The palindrome partitioning ["aa", "b"] could be produced using 1 cut between 'aa' and 'b'.
example_2.py — Already Palindrome
$
Input:
s = "aba"
›
Output:
0
💡 Note:
The entire string "aba" is already a palindrome, so no cuts are needed.
example_3.py — Multiple Cuts Needed
$
Input:
s = "abcde"
›
Output:
4
💡 Note:
Each character must be separated since no adjacent characters form palindromes: ["a", "b", "c", "d", "e"] requires 4 cuts.
Constraints
- 1 ≤ s.length ≤ 2000
- s consists of lowercase English letters only
- Optimization needed: Naive O(n³) solution may be too slow for larger inputs
Visualization
Tap to expand
Understanding the Visualization
1
Examine the strip
First, identify which sections of the paper have symmetric patterns (palindromes)
2
Plan the cuts
Use dynamic programming to determine the minimum cuts needed
3
Make optimal cuts
Cut at positions that result in all symmetric pieces with fewest cuts
Key Takeaway
🎯 Key Insight: Pre-compute all palindromic substrings, then use DP to find the minimum cuts by building up from smaller subproblems
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code