Home
DSA Patterns
Backtracking
Palindrome Partitioning
Palindrome Partitioning (LeetCode 131)
Palindrome Partitioning (LeetCode 131): list every way to cut a string into palindromes with backtracking: cut a palindrome off the front, partition the rest, undo.
Problem Understanding
Palindrome Partitioning: split the string s so that every piece is a palindrome, and return every such partition.
Example: "aab" returns [["a", "a", "b"], ["aa", "b"]].
The Intuition: Choose the First Piece
Every partition starts with some piece s[0..end), and that piece must be a palindrome. Once it is cut off, what remains is the same problem on a shorter string.
Backtracking turns that into code with one shared path:
- If
startis the end of the string, the path is a full partition: record it. - Otherwise, for each
endafterstart, skips[start..end)unless it is a palindrome. - Append the palindrome, partition from
end, then pop it and try a longer piece.
The skipped pieces prune the tree: no partition can start with a piece that is not a palindrome.
Palindrome Partitioning Visualization
EVERY PIECE MUST READ THE SAME BOTH WAYS
START
Path
:
Found
0
partitions
None yet
Partition "aab": cut a palindrome off the front, then partition the rest
Next
"a" is a palindrome: cut it off and partition what is left from 1
s
Pieces already cut into the path are shaded, with a gap after each one. The piece being tried is filled, or outlined in red when it is not a palindrome. Recorded partitions collect beside the string.
Palindrome Partitioning Dry Run
Input: "aab"
| First piece | Rest | Partitions of the rest | Result |
|---|---|---|---|
| a | ab | a, b | [a, a, b] |
| aa | b | b | [aa, b] |
| aab | - | not a palindrome | skipped |
Two partitions.
Palindrome Partitioning LeetCode Solution
Backtracking over the first piece: skip non-palindromes, choose, recurse, undo.
Palindrome Partitioning Code
1var partition = function(s) {2 const out = [], path = [];3 const isPal = (l, r) => {4 while (l < r) if (s[l++] !== s[r--]) return false;5 return true;6 };7 const backtrack = (start) => {8 if (start === s.length) {9 out.push([...path]);10 return;11 }12 for (let end = start + 1; end <= s.length; end++) {13 if (!isPal(start, end - 1)) continue;14 path.push(s.slice(start, end));15 backtrack(end);16 path.pop();17 }18 };19 backtrack(0);20 return out;21};
Palindrome Partitioning in Python, Java, C++, TypeScript and C
Palindrome Partitioning in Python
class Solution:
def partition(self, s: str) -> List[List[str]]:
out, path = [], []
def backtrack(start):
if start == len(s):
out.append(path[:])
return
for end in range(start + 1, len(s) + 1):
piece = s[start:end]
if piece != piece[::-1]:
continue
path.append(piece)
backtrack(end)
path.pop()
backtrack(0)
return outPalindrome Partitioning in Java
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> out = new ArrayList<>();
backtrack(s, 0, new ArrayList<>(), out);
return out;
}
private void backtrack(String s, int start, List<String> path, List<List<String>> out) {
if (start == s.length()) {
out.add(new ArrayList<>(path));
return;
}
for (int end = start + 1; end <= s.length(); end++) {
if (!isPalindrome(s, start, end - 1)) continue;
path.add(s.substring(start, end));
backtrack(s, end, path, out);
path.remove(path.size() - 1);
}
}
private boolean isPalindrome(String s, int l, int r) {
while (l < r) if (s.charAt(l++) != s.charAt(r--)) return false;
return true;
}
}Palindrome Partitioning in C++
class Solution {
vector<vector<string>> out;
vector<string> path;
bool isPalindrome(const string& s, int l, int r) {
while (l < r) if (s[l++] != s[r--]) return false;
return true;
}
void backtrack(const string& s, int start) {
if (start == (int)s.size()) {
out.push_back(path);
return;
}
for (int end = start + 1; end <= (int)s.size(); end++) {
if (!isPalindrome(s, start, end - 1)) continue;
path.push_back(s.substr(start, end - start));
backtrack(s, end);
path.pop_back();
}
}
public:
vector<vector<string>> partition(string s) {
backtrack(s, 0);
return out;
}
};Palindrome Partitioning in TypeScript
function partition(s: string): string[][] {
const out: string[][] = [], path: string[] = [];
const isPal = (l: number, r: number): boolean => {
while (l < r) if (s[l++] !== s[r--]) return false;
return true;
};
const backtrack = (start: number): void => {
if (start === s.length) {
out.push([...path]);
return;
}
for (let end = start + 1; end <= s.length; end++) {
if (!isPal(start, end - 1)) continue;
path.push(s.slice(start, end));
backtrack(end);
path.pop();
}
};
backtrack(0);
return out;
}Palindrome Partitioning in C
static char*** out;
static int* sizes;
static int count;
static char* path[16];
static bool isPal(char* s, int l, int r) {
while (l < r) if (s[l++] != s[r--]) return false;
return true;
}
static void backtrack(char* s, int n, int start, int depth) {
if (start == n) {
out[count] = malloc(depth * sizeof(char*));
for (int k = 0; k < depth; k++) out[count][k] = strdup(path[k]);
sizes[count++] = depth;
return;
}
for (int end = start + 1; end <= n; end++) {
if (!isPal(s, start, end - 1)) continue;
path[depth] = strndup(s + start, end - start);
backtrack(s, n, end, depth + 1);
free(path[depth]);
}
}
char*** partition(char* s, int* returnSize, int** returnColumnSizes) {
int n = strlen(s);
out = malloc(32768 * sizeof(char**));
sizes = malloc(32768 * sizeof(int));
count = 0;
backtrack(s, n, 0, 0);
*returnSize = count;
*returnColumnSizes = sizes;
return out;
}Edge Cases & Common Mistakes
- Recording the path itself: append a copy (
path[:],new ArrayList<>(path)), or every recorded partition changes as the path is undone. - Single letters: every single character is a palindrome, so at least one partition always exists.
- Off-by-one in the slice:
s[start:end]excludesend; the palindrome check must useend − 1as its right index. - Repeated checks: checking the same substring many times is wasteful on long strings; a DP palindrome table makes each check O(1).
Summary
Cut a palindromic first piece, partition the rest recursively, and undo to try a longer piece. Record the path when the whole string is cut. Non-palindromic pieces are skipped, which prunes the search. O(n · 2^n) time in the worst case.
More practice: DSA interview questions with answers · patterns cheat sheet
