Palindrome Partitioning – Solution & Complexity
Solution Walkthrough
1. Define the search state
- A partition is built from left to right, so the recursive state can simply be the starting index of the next substring plus the current path of chosen pieces.
- At each step, try every possible ending index for the next piece, but only continue if that piece is a palindrome.
2. Brute-force baseline
- The brute-force version tries every way to place separators between characters, then checks whether each produced substring is a palindrome.
- That wastes a lot of work because the same substring gets tested repeatedly across many recursive branches.
3. Cache palindrome checks
- Precompute
is_pal[left][right]with dynamic programming: a substring is a palindrome when its ends match and its interior is also a palindrome (or has length at most 2). - Then the DFS can test whether a candidate piece is legal in
O(1)time and keep the output in deterministic left-to-right DFS order.
4. Final solution (all languages)
The preprocessing table costs O(n^2), and the backtracking cost is proportional to the number of valid partitions produced.
5. Common mistakes and follow-ups
- Returning the same mutable
pathbuffer repeatedly instead of copying it when a full partition is found. - Losing deterministic output order by exploring longer prefixes before shorter ones.
- Follow-up: if the interviewer asks for minimum cuts only, this turns into a dynamic-programming optimization problem instead of an output-all backtracking problem.