Palindrome Partitioning

medium

Given a string s, split it into consecutive pieces so that every piece reads the same forwards and backwards — a palindrome. Return all such partitionings.

A partition keeps the original left-to-right order of s; you only decide where to cut. Because every single character is itself a palindrome, at least one valid partition always exists.

Return the list of partitions in any order; within a partition the pieces appear in the order they occur in s.

Hints

Every single letter is already a palindrome, so you can always fall back to cutting between every character — what extra freedom do longer palindromic pieces buy you?
Fix the first piece: try every prefix, and whenever that prefix is a palindrome, solve the very same problem on the remaining suffix.
The palindrome test keeps repeating on the same substrings — cache all answers in a boolean table pal[i][j] built from the inside out so each check is O(1).

Common doubts

Yes. A partition only chooses where to cut; it never rearranges characters, so the pieces read left to right exactly as in s.
Yes. Every single character is a palindrome, so the all-singletons partition is always one valid answer.
The number of partitions can grow like 2^(n-1). An exponential-sized answer is unavoidable, so the input is kept tiny.

Interview follow-ups

That is Palindrome Partitioning II — drop the enumeration and run a 1-D DP over cut positions on top of the same palindrome table.
Do a DP that sums, over each palindromic prefix, the count for the remaining suffix — this avoids materializing the exponential output.

Fun facts

  • The palindrome table pal[i][j] is the exact same trick that powers Longest Palindromic Substring.
  • A string of n identical characters has 2^(n-1) palindrome partitions — the same count as the compositions of the integer n.

Asked at

AmazonGoogleMicrosoftMetaBloomberg
Frequently Sometimes Occasionally
Example 1
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]
"a","a","b" are each palindromes, and so are "aa","b".
Example 2
Input: s = "a"
Output: [["a"]]
A single character is already a palindrome.
Constraints

- 1 <= s.length <= 16 - s contains only lowercase English letters.

Solve this problem →