Learn / Recursion and backtracking

Palindrome partitioning

Cut the string from left to right. At each position, try every next piece that is a palindrome, recurse on the rest, and undo. When the cuts reach the end, the pieces are one valid partition.

How to recognise it

  • A string must be split into pieces that each satisfy a rule (palindromes, dictionary words).
  • The question asks for every way to split it.

The idea in one picture

Hold scissors over the string. Make the first cut after any palindrome that starts at the left end. Then do the same for what is left. When nothing is left, the cuts you made form one partition.

Template

function cut(start, parts):
    if start == n: record a copy of parts; return
    for end from start + 1 to n:
        piece = s[start .. end - 1]
        if piece is a palindrome:
            add piece; cut(end, parts); remove it

A table pal[i][j] built in O(n²) beforehand makes each palindrome check O(1).

Common mistakes

  • Recording parts itself instead of a copy.
  • Re-checking the same piece many times on long strings without a table.
  • Forgetting that a single character is always a palindrome.

Problems

0 of 1 solved

Check yourself

How many ways are there to cut a string of length n into pieces, ignoring the palindrome rule?

Why check the palindrome rule before recursing, not after the whole partition is built?

For "aab", which partitions are valid?