Skills101
← All coding problems

Palindrome Partitioning

mediumRecursion & Backtracking+20 XPTime limit 2s

Split the string into pieces so that every piece is a palindrome. Print every possible way.

Input: one line s (lowercase letters).

Output:

  • line 1: the number of partitions p
  • next p lines: one partition each, its pieces in order separated by spaces

List the partitions in lexicographic order, comparing piece by piece (so a a b comes before aa b).

Constraints: 1 ≤ length of s ≤ 16.

Think about it: backtrack over the end of the first piece; recurse on the rest only if the piece is a palindrome. Precomputing isPal[i][j] with DP avoids re-checking the same substrings. Trying shorter first pieces first produces exactly the required order.

Sample input 1

aab

Sample output 1

2
a a b
aa b

Sample input 2

a

Sample output 2

1
a

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.