SDE & MLE Prep

131. Palindrome Partitioning

Problem

Split s into pieces that are all palindromes, and return every possible way to do so.

Example: "aab" → [["a","a","b"],["aa","b"]]

Constraints: length ≤ 16.

At index i, try every end j where s[i..j] is a palindrome, recurse from j+1. (Precompute a palindrome table to make checks O(1).)

Complexity: O(n · 2ⁿ).

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        res, path = [], []

        def bt(i):
            if i == len(s):
                res.append(path[:])
                return
            for j in range(i, len(s)):
                piece = s[i:j + 1]
                if piece == piece[::-1]:
                    path.append(piece)
                    bt(j + 1)
                    path.pop()

        bt(0)
        return res