Palindrome Partitioning solution explained
Palindrome Partitioning asks for every way to cut a string into pieces that each read the same in both directions. The standard solution is backtracking: choose the first piece from every palindromic prefix, recurse on the rest, and undo the choice on the way back, with a precomputed table so each palindrome check is O(1). The output itself can hold up to 2^(n-1) splits, so the running time is O(n · 2^n) in the worst case.
By Evin JohnPublished 10 min read
The problem, restated
You get a string of lowercase letters. Cut it into consecutive pieces, keeping every letter in order and using each letter exactly once, so that each piece is a palindrome. Return all the different ways to do this. A single letter is always a palindrome, so at least one valid split exists for any non-empty string: the one that cuts between every pair of letters.
"noon" -> [n, o, o, n]
[n, oo, n]
[noon]
"refer" -> [r, e, f, e, r]
[r, efe, r]
[refer]
"abc" -> [a, b, c] (only the single-letter split)Questions to settle before coding: does the order of the splits in the output matter (usually not), can the string be empty, and roughly how long can it get? Length matters a lot here. Because the answer can be exponential in size, inputs for this problem are normally kept short, often well under twenty characters. If the interviewer says the string may be thousands of letters long, they probably want a count or the minimum number of cuts, not the full list.
Why interviewers like it
It is a clean test of the choose, explore, unchoose rhythm of backtracking, with one extra layer: a smart candidate notices that the same substring gets checked over and over and caches those checks. The question also opens naturally into dynamic programming through its follow-ups, so a single problem can cover two topics in one session.
- Can you see the recursion tree? Each level picks where the next piece ends.
- Do you copy the path at the right moment? Appending the live list instead of a copy is the classic bug.
- Can you state an honest bound? The output size dominates, and saying so is better than claiming a polynomial time.
- Can you switch modes for the follow-up? Minimum cuts needs a DP, not a search.
Brute force: try every set of cuts
A string of length n has n − 1 gaps between letters, and each gap is either cut or not. That gives 2^(n-1) candidate splits. Enumerate them with a bitmask, slice the string at the chosen gaps, and keep the split if every piece is a palindrome. Each candidate costs O(n) to slice and check, so the total is O(n · 2^n). That is the same worst-case order as the good solution, which surprises people. The difference shows up on typical strings: brute force pays for every candidate, while backtracking abandons a branch as soon as a prefix fails.
def partitions_slow(s):
n = len(s)
if n == 0:
return [[]]
result = []
for mask in range(1 << (n - 1)):
pieces, start = [], 0
for gap in range(n - 1):
if mask >> gap & 1:
pieces.append(s[start:gap + 1])
start = gap + 1
pieces.append(s[start:])
if all(p == p[::-1] for p in pieces):
result.append(pieces)
return resultThe standard solution: backtracking plus a palindrome table
Think of the search as walking along the string. Standing at index start, you choose where the next piece ends. For each end from start to the last index, if s[start..end] is a palindrome, push that piece, move to end + 1, and continue. When start reaches the end of the string, the current path is one complete answer, so save a copy. Then pop the piece and try the next end.
The palindrome test is where the cache pays off. Without it, each test scans the substring, and the same substring is tested from many branches. Build a table pal[i][j] first: a substring is a palindrome when its two end letters match and the part strictly inside is a palindrome too (or has fewer than two letters). Fill it with i running from the end of the string backward, so pal[i + 1][j − 1] is always ready when you need it. That costs O(n²) time and space once, and every later check is a lookup.
def palindrome_partitions(s):
n = len(s)
pal = [[False] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(i, n):
if s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1]):
pal[i][j] = True
result, path = [], []
def explore(start):
if start == n:
result.append(path[:]) # copy, the path keeps changing
return
for end in range(start, n):
if pal[start][end]:
path.append(s[start:end + 1])
explore(end + 1)
path.pop()
explore(0)
return resultfunction palindromePartitions(s) {
const n = s.length;
const pal = Array.from({ length: n }, () => new Uint8Array(n));
for (let i = n - 1; i >= 0; i--) {
for (let j = i; j < n; j++) {
if (s[i] === s[j] && (j - i < 2 || pal[i + 1][j - 1])) pal[i][j] = 1;
}
}
const result = [];
const path = [];
const explore = (start) => {
if (start === n) {
result.push(path.slice());
return;
}
for (let end = start; end < n; end++) {
if (!pal[start][end]) continue;
path.push(s.slice(start, end + 1));
explore(end + 1);
path.pop();
}
};
explore(0);
return result;
}Both versions return [[]] for an empty string: one split with no pieces. Some interviewers prefer an empty list there, so mention the choice rather than leave it to chance. Recursion depth equals the number of pieces in the current path, which is at most n, and n is small for this problem, so recursion is safe here in a way it is not on a large grid.
Complexity
| Approach | Time | Extra space (besides the output) |
|---|---|---|
| Every bitmask of cuts | O(n · 2^n) always | O(n) per candidate |
| Backtracking, checking each piece by scanning | O(n² · 2^n) worst case | O(n) recursion and path |
| Backtracking with the pal table | O(n · 2^n) worst case, far less on most strings | O(n²) table plus O(n) path |
| Minimum cuts DP (follow-up) | O(n²) | O(n²) table, or O(n) with center expansion |
The worst case is a string like "aaaa…", where every piece is a palindrome and all 2^(n-1) splits are valid. Copying each split costs up to O(n), which is where the n in O(n · 2^n) comes from. No algorithm can beat the size of what it must print, so this bound is tight for the listing version. On a string with few repeated letters, most branches die after one step and the search is close to linear.
The follow-up: fewest cuts
If the interviewer asks only for the minimum number of cuts so that every piece is a palindrome, stop listing. Let cuts[j] be the fewest cuts for the prefix ending at index j. If the whole prefix s[0..j] is a palindrome, cuts[j] is 0. Otherwise, try every i from 1 to j where s[i..j] is a palindrome and take cuts[i − 1] + 1. With the same table, that is O(n²) time. For "noon" the answer is 0, for "refer" it is 0, and for "abc" it is 2.
def min_palindrome_cuts(s):
n = len(s)
if n == 0:
return 0
pal = [[False] * n for _ in range(n)]
cuts = [0] * n
for j in range(n):
best = j # cut after every letter
for i in range(j + 1):
if s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1]):
pal[i][j] = True
best = 0 if i == 0 else min(best, cuts[i - 1] + 1)
cuts[j] = best
return cuts[-1]This version fills the table column by column instead of row by row, which works because pal[i + 1][j − 1] belongs to the previous column and is already set when column j is filled. It is a nice detail to point out if you have time: the order of filling a DP table is part of the solution, not an afterthought.
Edge cases worth testing
- Empty string: decide between [[]] and [] and say which.
- One letter: exactly one split.
- All letters different, such as "abc": only the single-letter split.
- All letters the same: 2^(n-1) splits, the stress case for time and memory.
- Even and odd length palindromes inside the string, like "oo" and "efe", to confirm the j − i < 2 base case covers both.
Mistakes that cost points
- Saving path itself instead of a copy, so every saved answer ends up empty after the pops.
- Filling the palindrome table in the wrong order and reading cells that are not set yet.
- Forgetting to pop after the recursive call, which leaks a piece into the next branch.
- Claiming O(n²) or O(n³) total time for the listing version. The output alone can be exponential.
- Using an off-by-one slice end, such as s[start:end] where the inclusive end needs end + 1.
How to explain it out loud
Fictional example
- Candidate
- Every answer is a sequence of choices: where does the first piece end, then where does the next one end. That is a recursion tree, so I will backtrack.
- Candidate
- The same substrings get checked from many branches, so I will precompute which ranges are palindromes. A range is one if its ends match and its inside is one, so I fill from the right end backward.
- Candidate
- At a leaf I copy the current path. For the bound, a string of identical letters has two to the n minus one valid splits, so the listing is exponential no matter what. The table only removes the extra factor from checking.
- Interviewer
- What if I only want the fewest cuts?
- Candidate
- Then I would not list anything. A one-dimensional DP over prefixes with the same table gives it in quadratic time.
Related problems
The same choose, explore, undo loop drives Letter Combinations of a Phone Number, where each level picks a letter instead of a cut, and N-Queens, where each level places a queen and pruning does most of the work. For a change of pattern, Surrounded Regions swaps recursion over choices for a flood fill on a board.
Practicing with Natively
Backtracking is easiest to learn when you can check your recursion tree against someone else's. During practice on Mac or Windows, Natively can read a problem like this one from a screenshot and suggest a plan, such as building the palindrome table first and copying the path at each leaf, and it transcribes your spoken explanation so you can hear where you rushed the complexity argument. See the AI interview assistant for the details.
Questions people ask
How do you solve Palindrome Partitioning?
Backtrack over where each piece ends. From the current index, try every end whose substring is a palindrome, add that piece, recurse on the rest, then remove it. Save a copy of the path whenever you reach the end of the string.
What is the time complexity of Palindrome Partitioning?
O(n · 2^n) in the worst case, because a string of one repeated letter has 2^(n-1) valid splits and each can take O(n) to copy. A precomputed palindrome table keeps each check at O(1).
Why precompute a palindrome table?
The search checks the same substrings from many branches. A table where a range is a palindrome when its end letters match and its inside is a palindrome costs O(n²) once and turns every later check into a lookup.
How do you find the minimum number of cuts instead?
Use dynamic programming over prefixes: the fewest cuts for a prefix is zero if it is a palindrome, otherwise one more than the best earlier prefix that leaves a palindromic last piece. That runs in O(n²).
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
