Palindrome Partitioning
Master this topic with zero to advance depth.
Palindrome Partitioning
Partitioning Strategy
A string can be partitioned in many ways. For Palindrome Partitioning, we only care about partitions where every substring is a palindrome.
The Decision Tree
At each step, we pick a substring s[start:end]. If it's a palindrome, we recurse on the remaining string s[end:].
Optimization with DP
Checking if a substring is a palindrome repeatedly is . We can precompute a 2D boolean array isPalindrome[i][j] using Dynamic Programming in to make each check .
Partition a string into all possible palindromic substrings. Includes visual cut-tree.
Examples
Level I: Standard Backtracking
Intuition
Try all possible prefixes. If a prefix is a palindrome, recurse on the suffix.
Iterate through the string. At each position, try taking a substring from the start to the current position. If it's a palindrome, add it to the path and recurse.
Detailed Dry Run
Dry Run: s="aab"
| Start | Substr | Is Pal? | Path | Action |
| :---- | :----- | :------ | :--- | :--- |
| 0 | "a" | YES | ["a"] | DFS(1) |
| 1 | "a" | YES | ["a","a"] | DFS(2) |
| 2 | "b" | YES | ["a","a","b"]| RES!! |
| 0 | "aa" | YES | ["aa"] | DFS(2) |
| 2 | "b" | YES | ["aa","b"] | RES!! |Level II: Backtracking with DP Precomputation
Intuition
Avoid repetitive palindrome checks by precomputing all possible palindromes in the string.
Create a 2D boolean array dp[i][j] where dp[i][j] is true if s[i:j+1] is a palindrome. Use the recurrence: dp[i][j] = (s[i] == s[j] && (j - i <= 2 || dp[i+1][j-1])).
Detailed Dry Run
s="aab" dp[0][0]=T, dp[1][1]=T, dp[2][2]=T dp[0][1] = (s[0]==s[1]) = T dp[1][2] = (s[1]==s[2]) = F dp[0][2] = (s[0]==s[2] && dp[1][1]) = F
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.