Palindrome Partitioning
Medium
Topics
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
s
partitions
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
s
partitions
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
- DFS from a start index.
- For each end >= start, if s[start..end] is a palindrome, add it and recurse from end+1.
- 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. Passingendre-considers the character you just consumed, so the search never advances and dies withRecursionError. 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 resimport java.util.*;
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> res=new ArrayList<>();
dfs(s,0,new ArrayList<>(),res);
return res;
}
boolean isPal(String s,int l,int r) {
while(l<r) {
if(s.charAt(l)!=s.charAt(r))return false;
l++;
r--;
}
return true;
}
void dfs(String s,int start,List<String> path,List<List<String>> res) {
if(start==s.length()) {
res.add(new ArrayList<>(path));
return;
}
for(int end=start;end<s.length();end++)if(isPal(s,start,end)) {
path.add(s.substring(start,end+1));
dfs(s,end+1,path,res);
path.remove(path.size()-1);
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<string>> partition(string s) {
vector<vector<string>> res;
vector<string> path;
function<bool(int,int)> isPal=[&](int l,int r) {
while(l<r) {
if(s[l]!=s[r])return false;
l++;
r--;
}
return true;
};
function<void(int)> dfs=[&](int start) {
if(start==(int)s.size()) {
res.push_back(path);
return;
}
for(int end=start;end<(int)s.size();end++)if(isPal(start,end)) {
path.push_back(s.substr(start,end-start+1));
dfs(end+1);
path.pop_back();
}
};
dfs(0);
return res;
}
};/**
* @param {string} s
* @return {string[][]}
*/ var partition = function(s) {
const res=[];
function isPal(l,r) {
while(l<r) {
if(s[l]!==s[r])return false;
l++;
r--;
}
return true;
}
function dfs(start,path) {
if(start===s.length) {
res.push(path.slice());
return;
}
for(let end=start;end<s.length;end++)if(isPal(start,end)) {
path.push(s.slice(start,end+1));
dfs(end+1,path);
path.pop();
}
}
dfs(0,[]);
return res;
};