Palindrome Partitioning (LeetCode 131): Solution and Explanation

Medium
String
Dynamic Programming
Backtracking

Given a string, split it into pieces so that every piece reads the same forwards and backwards. Return every possible way to do that split.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A string of length n has n - 1 gaps between characters, and each gap is either a cut or not. That gives 2^(n-1) ways to split the string, and a brute force would generate all of them and keep the ones where every piece is a palindrome. That is actually the right order of magnitude, because a string like aaaa has every split valid, but generating splits blindly wastes effort on partitions that fail early.

Backtracking does better by deciding one piece at a time, left to right. From the current position i, try every possible end j for the next piece. If s[i..j] is a palindrome, commit to it and recurse from j + 1. If it is not, skip it immediately and never explore any partition that would start with that piece. When i reaches the end of the string, every piece chosen along the way is a palindrome, so the current list is a valid answer.

This turns the problem into a tree. Each node is a starting position, each edge is a palindromic prefix of the remaining suffix, and each root-to-leaf path is one partition. The palindrome check is the pruning rule that keeps dead branches from growing.

The reference solution checks palindromes with a simple two-pointer helper isPali that walks inward from both ends. That costs O(n) per check, which is fine because the output itself can be exponentially large, so precomputing a palindrome table only improves the constant factor.

Approach: Backtracking over palindromic prefixes

  1. Keep res for finished partitions and part for the pieces chosen so far.
  2. Define dfs(i). If i >= len(s), the whole string has been split, so append a copy of part to res.
  3. Otherwise loop j from i to len(s) - 1, considering s[i:j+1] as the next piece.
  4. Check the piece with isPali(s, i, j), which compares characters from both ends moving inward.
  5. If it is a palindrome, append it to part, call dfs(j + 1), then pop it to try the next end.
  6. Call dfs(0) and return res.

Step-by-step example

s = "aab"
  1. dfs(0), j = 0: "a" is a palindrome. part = [a], call dfs(1).
  2. dfs(1), j = 1: "a" is a palindrome. part = [a, a], call dfs(2). There, "b" is a palindrome, so part = [a, a, b] and dfs(3) records it.
  3. Back in dfs(1), j = 2: "ab" is not a palindrome, so it is skipped.
  4. Back in dfs(0), j = 1: "aa" is a palindrome. part = [aa], call dfs(2), which takes "b" and records [aa, b].
  5. In dfs(0), j = 2: "aab" is not a palindrome. The result is [[a, a, b], [aa, b]].

Code: Python, Java, C++

1class Solution:
2    def partition(self, s: str) -> List[List[str]]:
3        res = []
4        part = []
5        
6        def dfs(i):
7            if i >= len(s):
8                res.append(part.copy())
9                return
10            
11            for j in range(i, len(s)):
12                if self.isPali(s, i, j):
13                    part.append(s[i:j+1])
14                    dfs(j + 1)
15                    part.pop()
16                    
17        dfs(0)
18        return res
19        
20    def isPali(self, s, l, r):
21        while l < r:
22            if s[l] != s[r]:
23                return False
24            l, r = l + 1, r - 1
25        return True

Time and space complexity

Time

O(n × 2^n)

There are up to 2^(n-1) partitions, which happens for a string of identical characters. Each one requires building and copying pieces of total length n, and the palindrome checks along each path also add O(n) work per level.

Space

O(n)

The recursion depth and the part list are at most n deep, not counting the output list.

Other approaches

Backtracking with a palindrome DP table (time O(n × 2^n), space O(n²))

Precompute isPal[i][j] for every substring using the rule that s[i..j] is a palindrome when its ends match and s[i+1..j-1] is one. Each check during backtracking then becomes O(1), which helps when the string has few valid partitions but many failed checks.

Bottom-up partition lists (time O(n × 2^n), space O(n × 2^n))

Build the list of partitions for every suffix, starting from the end. For each start i, combine each palindromic prefix with every stored partition of the remaining suffix. It avoids recursion but stores many intermediate lists.

Common mistakes

  • Slicing with s[i:j] instead of s[i:j+1], which drops the last character of every piece and yields empty strings.
  • Appending part itself to the result. The list keeps changing as you backtrack, so you must store part.copy().
  • Forgetting to pop after the recursive call, which leaves stale pieces in part and corrupts later partitions.
  • Confusing this with Palindrome Partitioning II, which asks only for the minimum number of cuts and needs dynamic programming rather than enumeration.

Frequently asked questions

What is the time complexity of Palindrome Partitioning?

It is O(n × 2^n). A string of identical characters has 2^(n-1) valid partitions, and producing each one takes O(n) work, so no algorithm that lists them all can do fundamentally better.

Why use backtracking for Palindrome Partitioning?

The problem asks for every valid partition, which is an enumeration task. Backtracking builds partitions piece by piece and abandons a branch as soon as a piece is not a palindrome.

Should I precompute palindromes with dynamic programming?

It is a useful optimization that makes each palindrome check constant time at the cost of an n by n table. It does not change the worst-case complexity, because the output size dominates.

How is this different from Palindrome Partitioning II?

This problem returns every partition. The second version asks for the minimum number of cuts, which you solve with dynamic programming in O(n²) without listing partitions.