Palindrome Partitioning II
Master this topic with zero to advance depth.
Palindrome Partitioning II
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Visual Representation
s = "aab"
Valid partitions:
["a", "a", "b"] -> 2 cuts
["aa", "b"] -> 1 cut (Min)
Result: 1Examples
The palindrome partitioning ["aa","b"] could be produced using 1 cut.
Level I: Brute Force (Recursion)
Intuition
Try every possible split point for the string. If the prefix is a palindrome, recursively find the minimum cuts for the remaining suffix.
Thought Process
solve(i)returns min cuts fors[i...n-1].- Base case: If
s[i...n-1]is a palindrome, return 0 (no more cuts needed). - For each
jfromiton-1:- If
s[i...j]is a palindrome:res = min(res, 1 + solve(j + 1)).
- If
Detailed Dry Run
s = "aab"
- "a" is pal. solve("ab")
- "aa" is pal. solve("b") -> "b" is pal, returns 0. Total 1+0=1. Result: 1
Level II: Memoization (Top-Down DP)
Intuition
Cache the result of solve(i) (min cuts for suffix s[i:]) using a memo array. Also precompute palindrome check to avoid O(N) palindrome check every time.
Visual
s = "aab"
memo[2] = 0 ("b" is palindrome)
memo[1] = 1 ("ab" -> "a"|"b" = 1 cut, or "ab" not pal)
memo[0] = 1 ("aa"|"b" = 1 cut, memo[2] cached!)Detailed Dry Run
s="aab". solve(2)=0. solve(1)=1+solve(2)=1. solve(0): is_pal[0][1]=True -> 1+solve(2)=1. Result=1.
Level III: Dynamic Programming (Two Passes)
Intuition
We need two DP arrays. One 2D array isPal[i][j] to precompute if s[i...j] is a palindrome. Another 1D array cuts[i] to store the minimum cuts needed for s[0...i].
Thought Process
- Precompute
isPal[i][j]using standard palindrome DP:s[i] == s[j] && (j-i < 2 || isPal[i+1][j-1]). - Initialize
cuts[i] = i(max possible cuts: each char separate). - For
jfrom 0 ton-1:- If
isPal[0][j]is true,cuts[j] = 0(no cuts needed for entire prefix). - Else, for
ifrom 1 toj:- If
isPal[i][j]is true,cuts[j] = min(cuts[j], cuts[i-1] + 1).
- If
- If
Detailed Dry Run
s = "aab" Precomputed isPal: [0,0]=T, [1,1]=T, [2,2]=T, [0,1]=T ("aa")
| j | isPal(0,j) | Action | cuts[j] |
|---|---|---|---|
| 0 | T | 0 cuts | 0 |
| 1 | T | 0 cuts | 0 |
| 2 | F | cuts[1]+1 ("aa" | "b") |
| Result: 1 |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.