Palindrome Partitioning

35 min · partition()

A string can tell several different mirror-stories depending on where you cut it. aab, for instance, has useful cuts after either the first or second a.

A palindrome is text that reads the same from left to right and right to left. Split the lowercase string s into non-empty pieces so every piece is a palindrome. Return every valid splitting.

Each result is an ordered list of pieces: joining that list must recreate s exactly. The collection of results itself may come back in any order.

Constraints

  • 1 <= s.length <= 12
  • s contains lowercase English letters only.
  • No input produces more than 2,048 partitionings.

Hints

Cuts are choices too

A string of length n has n - 1 gaps between characters. Each gap is either cut or uncut, so you can enumerate every cut pattern and filter the bad ones.

Choose the next piece

From a starting index, try every possible ending index. Recurse only when s[start:end + 1] is a palindrome.

Undo the piece

Add a palindromic prefix to the current partition, search from the next unread character, then remove that piece. Reaching the end means the current list is one complete answer.

Follow-up

Could you precompute which substrings are palindromes so the search never scans the same substring twice?

Visible cases

Examples

Example 1

ready
Input
s = "aab"
Expected
[
  [
    "a",
    "a",
    "b"
  ],
  [
    "aa",
    "b"
  ]
]
Why
both single a's and the combined aa are palindromes

Example 2

ready
Input
s = "a"
Expected
[
  [
    "a"
  ]
]
Why
one character is already a palindrome

Example 3

ready
Input
s = "abc"
Expected
[
  [
    "a",
    "b",
    "c"
  ]
]
Why
no multi-character piece is palindromic

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite