Skip to content

Palindrome Partitioning

List every way to cut a string into palindromes by choosing the next palindromic piece and backtracking.

MediumBacktracking
Solve on LeetCode

The problem

You get a string s. Split it into pieces so that every piece is a palindrome, meaning it reads the same forwards and backwards. Return every possible split, each one as the list of its pieces from left to right; the splits can be in any order.

Input s = "noon"

Output [["n", "o", "o", "n"], ["n", "oo", "n"], ["noon"]]

Single letters always work, "oo" is a palindrome in the middle, and the whole word is one too.

Input s = "abc"

Output [["a", "b", "c"]]

No piece longer than one letter reads the same backwards, so the only split is into single letters.

Key constraint: s has at most 16 letters, and a string of n equal letters has 2^(n - 1) valid splits, so the output itself can be exponential.

How to spot the pattern

  • You must list every way to cut the input, not count them or find the best one.
  • Each step chooses where the next piece ends, and only palindromic pieces are allowed.

The idea

Look at the first piece of any valid split: it is some palindrome s[0..end], and the rest of the string must again be split into palindromes. So try every end for which the first piece is a palindrome, cut it off, split the remaining suffix the same way, then undo the cut and try the next end. Reaching the end of the string means every piece so far was valid, so the current list of pieces is one answer.

Brute force: Try all 2^(n - 1) ways to place cuts and keep the splits whose pieces are all palindromes, which also builds every split that fails.

Step by step

  1. 1Write backtrack(start), which splits s[start:] and adds its pieces to a shared list current.
  2. 2If start equals the length of s, save a copy of current and return.
  3. 3Try every end from start to the last index, skipping it unless s[start..end] is a palindrome.
  4. 4Append that piece, call backtrack(end + 1), then remove the piece again.

See the pattern move

The backtracking pattern on a small example. Step through it, or press play.

Code

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

        def is_palindrome(lo: int, hi: int) -> bool:
            while lo < hi:
                if s[lo] != s[hi]:
                    return False
                lo += 1
                hi -= 1
            return True

        def backtrack(start: int) -> None:
            if start == len(s):
                result.append(current.copy())
                return
            for end in range(start, len(s)):
                if is_palindrome(start, end):  # only cut off palindromic pieces
                    current.append(s[start:end + 1])
                    backtrack(end + 1)
                    current.pop()

        backtrack(0)
        return result

Complexity

Time

O(n * 2^n)

Space

O(n)

There can be up to 2^(n - 1) splits and each takes O(n) to check and copy; the recursion and current hold at most n pieces, not counting the output.

Watch out for

  • Saving current itself instead of a copy, so every saved split changes as you backtrack.
  • Off-by-one slicing: the piece from start to end inclusive is s[start:end + 1].
  • Cutting off a piece without checking that it is a palindrome, and filtering only at the end.

Follow-up questions

How do you avoid checking the same substring again and again?

Fill a table first: s[i..j] is a palindrome when s[i] == s[j] and s[i + 1..j - 1] is one too (or is empty). Each check during the backtracking then takes O(1).

What if you only need the fewest cuts?

Use DP: cuts[i] is the fewest cuts for s[0..i], found by trying every palindrome that ends at i. That is Palindrome Partitioning II and runs in O(n^2).

In Hinglish

Shuru se ek palindrome tukda kaato, baaki string ke liye yahi kaam recursion se karo, phir tukda hata ke agla try karo. String khatam ho gayi toh current list ek answer hai.

Related problems