CodingNodes / Backtracking / Palindrome Partitioning System design Space play · ←→ step · R restart

Problem

You are given a string s. Cut it into consecutive pieces so that every piece is a palindrome, meaning it reads the same forwards and backwards.

Return every different way to cut s this way. Each way is a list of the pieces from left to right, and the ways may be returned in any order.

Constraints

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

Examples: pick one to animate

Solutions

TimeO(n · 2^n) SpaceO(n)

Time: There are n - 1 gaps between letters, each cut or not, so at most 2^n partitions. Checking a piece and copying a finished partition each cost O(n).

Space: Besides the output, the path holds at most n pieces and the recursion is at most n deep.

From position start, try every end end. If s[start..end] is a palindrome, cut it off, recurse from end + 1, then take it back. When start reaches the end of the string, the pieces in the path are a valid partition, so save a copy.