Palindrome Partitioning (LeetCode 131): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Keep
resfor finished partitions andpartfor the pieces chosen so far. - Define
dfs(i). Ifi >= len(s), the whole string has been split, so append a copy ofparttores. - Otherwise loop
jfromitolen(s) - 1, considerings[i:j+1]as the next piece. - Check the piece with
isPali(s, i, j), which compares characters from both ends moving inward. - If it is a palindrome, append it to
part, calldfs(j + 1), then pop it to try the next end. - Call
dfs(0)and returnres.
Step-by-step example
s = "aab"
dfs(0), j = 0: "a" is a palindrome.part= [a], calldfs(1).dfs(1), j = 1: "a" is a palindrome.part= [a, a], calldfs(2). There, "b" is a palindrome, sopart= [a, a, b] anddfs(3)records it.- Back in
dfs(1), j = 2: "ab" is not a palindrome, so it is skipped. - Back in
dfs(0), j = 1: "aa" is a palindrome.part= [aa], calldfs(2), which takes "b" and records [aa, b]. - 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 True1class Solution {
2 public List<List<String>> partition(String s) {
3 List<List<String>> res = new ArrayList<>();
4 List<String> part = new ArrayList<>();
5 dfs(0, s, part, res);
6 return res;
7 }
8
9 private void dfs(int i, String s, List<String> part, List<List<String>> res) {
10 if (i >= s.length()) {
11 res.add(new ArrayList<>(part));
12 return;
13 }
14
15 for (int j = i; j < s.length(); j++) {
16 if (isPali(s, i, j)) {
17 part.add(s.substring(i, j + 1));
18 dfs(j + 1, s, part, res);
19 part.remove(part.size() - 1);
20 }
21 }
22 }
23
24 private boolean isPali(String s, int l, int r) {
25 while (l < r) {
26 if (s.charAt(l) != s.charAt(r)) return false;
27 l++;
28 r--;
29 }
30 return true;
31 }
32}1class Solution {
2public:
3 vector<vector<string>> partition(string s) {
4 vector<vector<string>> res;
5 vector<string> part;
6 dfs(0, s, part, res);
7 return res;
8 }
9
10 void dfs(int i, string s, vector<string>& part, vector<vector<string>>& res) {
11 if (i >= s.size()) {
12 res.push_back(part);
13 return;
14 }
15
16 for (int j = i; j < s.size(); j++) {
17 if (isPali(s, i, j)) {
18 part.push_back(s.substr(i, j - i + 1));
19 dfs(j + 1, s, part, res);
20 part.pop_back();
21 }
22 }
23 }
24
25 bool isPali(string& s, int l, int r) {
26 while (l < r) {
27 if (s[l] != s[r]) return false;
28 l++;
29 r--;
30 }
31 return true;
32 }
33};Time and space complexity
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.
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 ofs[i:j+1], which drops the last character of every piece and yields empty strings. - Appending
partitself to the result. The list keeps changing as you backtrack, so you must storepart.copy(). - Forgetting to pop after the recursive call, which leaves stale pieces in
partand 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.