Palindrome PartitioningLoading saved progress…

Palindrome Partitioning

Palindrome partitioning asks for every way to cut a string into contiguous pieces where each piece is a palindrome — a run of characters that reads the same forwards and backwards, like aa, b, or racecar. This is LeetCode 131. For aab there are exactly two such splits: a | a | b and aa | b. You return them as a list of partitions, where each partition is an array of its pieces in left-to-right order.

Signature

palindromePartitioning(s)  // string -> array of partitions (each partition an array of palindrome pieces)

Examples

palindromePartitioning('aab');
// [['a', 'a', 'b'], ['aa', 'b']]
palindromePartitioning('a');
// [['a']]
palindromePartitioning('aba');
// [['a', 'b', 'a'], ['aba']]

Notes

  • Every piece is a palindrome — a single character always reads the same both ways, so a partition always exists; in the worst case you cut every character apart.
  • Pieces cover the whole string — concatenating a partition's pieces in order reproduces s exactly, with nothing dropped, added, or reordered.
  • Order is not specified — return the partitions (and find the pieces within each) in any order; only the collection of partitions matters, not its arrangement.
  • Empty stringpalindromePartitioning('') returns [[]]: a single partition that contains no pieces.
  • Build it yourself — no libraries; the whole point is the search over cut positions.

FAQ

Why does checking the piece is a palindrome before recursing matter?
It is what turns brute force into a fast search. If you only test pieces at the end of a full slicing, you explore all 2^(n-1) ways to cut the string. Guarding the recursive call behind the palindrome check prunes an entire branch the moment its leading piece fails, so doomed cut-sets like the ones starting with ab are never expanded.
Why push a copy of the path instead of the path itself?
The path array is reused across the whole search and is mutated by push and pop as the recursion backtracks. Storing a live reference would give you an array that is empty by the time the search finishes, so every answer would come out as []. Snapshotting with path.slice() (or the spread [...path]) freezes the current pieces.
How many partitions can there be?
In the worst case, a string of n identical characters like aaaa, the number of palindrome partitions is 2^(n-1), because every gap can independently be a cut. That exponential output size is why the problem is about enumeration, not a single answer, and why minimum-cuts (LeetCode 132) is a different, polynomial problem.
Loading editor…