Palindrome Partitioning

MediumBacktrackingLeetCode 131 ↗World 4-14
0:00 / 0:00

Split a string into palindromes every possible way. Cut off a palindrome prefix, recurse on the rest, then undo the cut and try a longer one.

▼

The problem

LeetCode 131 (Medium). Given a string s, partition it so that every substring of the partition is a palindrome, and return all possible palindrome partitionings.

Example: s = "aab" → [["a","a","b"],["aa","b"]].

TRY IT ON LEETCODE ▶

The solution

def partition(s):
    res, path = [], []
    def back(start):
        if start == len(s):
            res.append(path[:])  # a copy
            return
        for end in range(start + 1, len(s) + 1):
            piece = s[start:end]
            if piece == piece[::-1]:  # mirror
                path.append(piece)
                back(end)
                path.pop()
    back(0)
    return res

Transcript

Palindrome Partitioning. Cut a string into pieces so that every piece is a palindrome, the same forwards and backwards. Return every way to do it.

Take A, A, B. Cut after every letter: A, A, B. Single letters are always palindromes, so that works. Or keep A A together, then B. That's two partitions.

The naive way: each gap between letters is cut or not, so n letters give two to the n minus one cut patterns. Make them all, then check the pieces. For A, B, B, A, that's eight patterns, and five of them fail, but you only find out at the end. Twenty letters means over half a million.

Backtracking checks as it cuts. From the start, try every end, and hold that piece up to a mirror. Not a palindrome? Skip it, and every partition that begins with it. A palindrome? Cut it, and solve the rest the same way, from the next letter. When the start reaches the end, the pieces form a partition: record it. Then undo the last cut and try the next end.

In code: if start equals the length, save a copy of the path. Otherwise, loop over every end. If that slice is a palindrome, push it, recurse from there, and pop it off.

Let's run A, A, B. A is a palindrome: cut it, and recurse. A again: cut. Then B, and start hits the end: record A, A, B. Pop back. A B fails the mirror: pruned. Pop again. A A works: cut, then B: record A A, B. Last, A A B fails. Two partitions.

Worst case, all A's: every piece is a palindrome, so all two to the n minus one patterns are partitions, each copied in order n. So the time is order n times two to the n. The recursion goes at most n deep, so the extra space is order n, not counting the output.

Try every end, cut only mirrors, and backtrack. That's Palindrome Partitioning.