Palindrome Partitioning

Medium

Topics
StringBacktrackingDynamic Programming

Given a string s, partition it so that every substring of the partition is a palindrome. Return all possible palindrome partitionings, in any order.

Example 1

saab
partitions[a,a,b][aa,b]
Every cut point is tried, but only a palindromic piece is recursed into — so the search prunes as it goes rather than filtering complete partitions at the end. Precomputing which substrings are palindromes turns each check into a table lookup. 2 partitions.
The string and each valid partition of it.
Input:  s = "aab"
Output: [["a","a","b"],["aa","b"]]

Example 2

sa
partitions[a]
Input:  s = "a"
Output: [["a"]]

Constraints

  • 1 <= s.length <= 16
  • s contains only lowercase English letters.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Try every prefix of the remaining string; whenever the prefix is a palindrome, fix it as the next piece and recurse on the rest. Each full split into palindromes is one answer.

Approach

  1. DFS from a start index.
  2. For each end >= start, if s[start..end] is a palindrome, add it and recurse from end+1.
  3. When start reaches the end of the string, record the current partition.

Dry Run

s = "aab"
At each position, try every prefix that is a palindrome and recurse past it:
  "a"  (s[0:1]) is a palindrome   path [a]
    "a"  (s[1:2]) is a palindrome   path [a, a]
      "b"  (s[2:3]) is a palindrome   path [a, a, b]   start reached the end: record
    "ab" is not a palindrome          skip
  "aa" (s[0:2]) is a palindrome   path [aa]
    "b"  (s[2:3]) is a palindrome   path [aa, b]       record
  "aab" is not a palindrome         skip
answer [a, a, b] and [aa, b]
The base case is `start == len(s)`, which means the partition is complete only when
every character has been consumed -- there is no partial credit. Non-palindromic
prefixes are not failures to recover from, they are simply branches never entered.
Two small things carry the whole function. Recursing from `end + 1` is what
advances: pass `end` and the same character is reconsidered forever, which dies
with RecursionError. And `res.append(path[:])` must copy -- append the list itself
and you store a reference that backtracking then empties, so this input returns
[[], []]: the right NUMBER of answers, all blank. That one is especially nasty,
because the count looks correct.

Complexity

  • Time — O(n * 2^n): up to 2^n partitions, each checked/copied in O(n).
  • Space — O(n): recursion depth.

Common Pitfalls

  • Recurse from end + 1. Passing end re-considers the character you just consumed, so the search never advances and dies with RecursionError.
  • res.append(path[:]) -- copy. Appending the list itself stores a reference that the backtracking then empties, so every result comes back blank.

Full Solution — all languages

class Solution:
    def partition(self, s):
        res=[]
        def isPal(l,r):
            while l<r:
                if s[l]!=s[r]: return False
                l+=1; r-=1
            return True
        def dfs(start,path):
            if start==len(s): res.append(path[:]); return
            for end in range(start,len(s)):
                if isPal(start,end):
                    path.append(s[start:end+1]); dfs(end+1,path); path.pop()
        dfs(0,[])
        return res
SensAI
Beta
Tap the mic to stop voice mode