iq.lab
Python starts when a code cell comes near or you run one
mediumBacktracking target 25 min

Cut a string into palindromes

A palindrome is a string that reads the same forwards and backwards, such as "level", "oo" or any single letter. You get a string s. Return every way to cut s into pieces of one or more letters so that every piece is a palindrome.

Write each way as a list of its pieces from left to right, so that joining the list gives back s. Return each way once, in any order. There is always at least one way: cutting s into single letters.

Example 1
Inputs = "noon"Output[["n", "o", "o", "n"], ["n", "oo", "n"], ["noon"]]

Single letters always work. "oo" is a palindrome, and so is the whole word. A piece such as "no" is not.

Example 2
Inputs = "abc"Output[["a", "b", "c"]]

"ab", "bc" and "abc" are not palindromes, so single letters are the only way.

Example 3
Inputs = "aaa"Output[["a", "a", "a"], ["a", "aa"], ["aa", "a"], ["aaa"]]

Every piece of "aaa" is a palindrome. Each of the 2 gaps between letters is cut or not, so all 4 ways count.

Constraints
  • 1 ≤ len(s) ≤ 24

  • s holds only lowercase English letters.

  • There are at most 5,000 ways to cut s into palindromes.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.