Palindrome Partitioning - Problem

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

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

Input & Output

Example 1 — Basic Case
$ Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
💡 Note: "a" and "aa" are palindromes, "b" is palindrome. Two valid partitions: split each character separately ["a","a","b"] or group first two ["aa","b"].
Example 2 — All Partitions
$ Input: s = "raceacar"
Output: [["r","a","c","e","a","c","a","r"],["r","a","c","e","aca","r"]]
💡 Note: The string contains the palindrome "aca" at positions 4-6. Two valid partitions: split each character separately or group the "aca" palindrome.
Example 3 — Single Character
$ Input: s = "a"
Output: [["a"]]
💡 Note: Single character is always a palindrome, only one partition possible.

Constraints

  • 1 ≤ s.length ≤ 16
  • s contains only lowercase English letters

Visualization

Tap to expand
Palindrome Partitioning Dynamic Programming + Backtracking Approach INPUT String s = "aab" a index 0 a index 1 b index 2 Palindrome Substrings: "a" (0,0) - OK "a" (1,1) - OK "b" (2,2) - OK "aa" (0,1) - OK Input Values: s = "aab" length = 3 ALGORITHM STEPS 1 Build DP Table Pre-compute palindrome checks for all substrings 2 Backtrack Start Start from index 0, try all valid partitions 3 Explore Paths For each palindrome prefix, recurse on remainder 4 Collect Results When reaching end, add partition to result Backtracking Tree: "aab" "a" "aa" "a" "b" FINAL RESULT All Valid Partitions: Partition 1: "a" "a" "b" OK Partition 2: "aa" "b" OK Output Array: [ ["a","a","b"], ["aa","b"] ] Total: 2 valid partitions Key Insight: Use DP to pre-compute O(n^2) palindrome checks, then backtrack through all valid partitions. At each position, try extending with every possible palindrome substring and recurse on the remainder. Time: O(n * 2^n) | Space: O(n^2) for DP table + O(n) recursion depth TutorialsPoint - Palindrome Partitioning | Dynamic Programming + Backtracking
Asked in
Amazon 45 Microsoft 38 Google 32 Facebook 28
87.5K Views
High Frequency
~25 min Avg. Time
2.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