Python coding

Every way to cut into palindromes

Cut the string s into consecutive pieces so that every piece is a palindrome: it reads the same backwards, like "noon" or "b". Return every such way to cut it, each one as the list of its pieces from left to right. A single character is always a palindrome, so there is at least one answer. Return each way once; the ways may come in any order, but the pieces inside a way keep their order.

1 ≤ len(s) ≤ 20, lowercase a–z.

Besides the tests, one large input (a 19-letter string) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • palindrome_cuts("aab") → [["a","a","b"],["aa","b"]]
  • palindrome_cuts("racecar") → [["r","a","c","e","c","a","r"],["r","a","cec","a","r"],["r","aceca","r"],["racecar"]]
  • palindrome_cuts("z") → [["z"]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Backtracking: build the cut one piece at a time, left to right. The only choice at each step is where the next piece ends.

Hint 2

From start, try every end: keep s[start:end] only if it is a palindrome, recurse from end, then pop it. Testing before recursing is the pruning: a failing piece removes every cut that begins with it.

Hint 3

When start reaches len(s), the pieces cover the whole string: record a copy of the path, not the path itself, which keeps changing.

Solution and why it works
pythonO(n·2ⁿ) in the worst case (all letters equal) · O(n) recursion depth, beyond the output
def palindrome_cuts(s: str) -> list[list[str]]:
    res, path = [], []

    def bt(start: int) -> None:
        if start == len(s):
            res.append(path[:])          # copy: path keeps changing
            return
        for end in range(start + 1, len(s) + 1):
            piece = s[start:end]
            if piece == piece[::-1]:     # prune: only a palindrome may continue
                path.append(piece)
                bt(end)
                path.pop()

    bt(0)
    return res

Each level chooses the next piece, s[start:end], and only a palindrome may continue, so a path that reaches the end of s is a valid cut, built exactly once. Rejecting a piece prunes every cut that begins with it. The trap is generating all 2ⁿ⁻¹ ways to cut and filtering afterwards: a 20-letter string has 524,288 of them even when only a handful are valid. Record path[:], not path, which keeps changing.