← Whiteboard questions

Palindrome Partitioning

Split a string so that every piece reads the same backwards

DSA, Medium, Backtracking

Which structure or algorithm, and what does it cost.

A string text holds lowercase letters. Cut it into consecutive pieces so that every piece is a palindrome. A palindrome reads the same forwards and backwards. Return every way to do this, each as a list of its pieces in order. List the ways in any order. A string of one letter has one way.

Examples

Input text = "abba"
Output [["a", "b", "b", "a"], ["a", "bb", "a"], ["abba"]]
Why a|b|b|a, a|bb|a and abba are the three ways.
Input text = "k"
Output [["k"]]
Why one letter is a palindrome, so there is one way.
Input text = "zzz"
Output [["z", "z", "z"], ["z", "zz"], ["zz", "z"], ["zzz"]]
Why every piece of z is a palindrome, so every way to cut works: 4 ways.

Constraints

Your answer must contain

Target Aim to drop a cut as soon as its piece is not a palindrome.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Decide where the first piece ends. Which first pieces are allowed?

Hint 2 the approach

After you keep a valid first piece, the rest of the string is the same question on a shorter string. Stop when no letters are left.

Hint 3 the key step

Keep a list of pieces and a start position. Try every end after start. If that slice reads the same backwards, add it, recurse from its end, then remove it.

Walkthrough

Full walkthrough brute force to best

Brute force

Try every way to cut: each of the n - 1 gaps between letters is cut or not, so there are 2^(n - 1) ways. For each way, check that every piece is a palindrome. The cost is O(n * 2^n), and most ways are thrown away at the end.

Best method

Keep the pieces chosen so far in a list and a start position. If the start position is the end of the string, record a copy of the list. Otherwise try every end position after start. Take the slice from start to that end. Only if it reads the same backwards, add it, call again from the end position, and remove it. A piece that is not a palindrome can never be part of an answer, so the whole branch below it is skipped. The search never builds a cut that has already failed.

Hand trace

Run on abba. From the start, a is a palindrome: take it. Then b: take it. Then b: take it. Then a: take it. The string is used up, so record [a, b, b, a]. Back at the third letter, ba is not a palindrome. Back at the second letter, bb is: take it, then a, and record [a, bb, a]. bba is not. Back at the start, ab and abb are not. abba is: record [abba]. Three ways.

Code

def palindrome_partitions(text):
    out = []
    pieces = []
    def go(start):
        if start == len(text):
            out.append(pieces[:])
            return
        for end in range(start + 1, len(text) + 1):
            piece = text[start:end]
            if piece == piece[::-1]:
                pieces.append(piece)
                go(end)
                pieces.pop()
    go(0)
    return out

Time and memory

O(n * 2^n) time in the worst case, for example when every letter is the same and all 2^(n - 1) ways work. Each tried piece costs up to n steps to test. Extra memory is O(n) for the pieces and the recursion, plus the answer.

Common mistakes

  • Testing palindromes only after all the cuts are made. The search then builds many cuts that already failed.
  • Leaving out the whole remaining string as a piece. The last end position must be the length of the string.
  • Recording the list of pieces itself, not a copy. Later removals empty it.

Related problems

More Backtracking problems
Palindrome Partitioning: walkthrough and Python solution