LeetCode #131 Medium

Palindrome Partitioning

Palindrome Partitioning is LeetCode 131 (Medium). Cut the string s into pieces so that every piece is a palindrome, and return every way of doing it. In other words, list all the palindromic partitions of s, in any order.

  • A single letter is always a palindrome, so there is always at least one answer: every letter on its own.
  • s has at most 16 letters. A string of one repeated letter has 2¹⁵ valid splits, so the output alone can be huge, and a search that lists them one by one is the expected approach.
Constraints
  • 1 <= s.length <= 16
  • s contains only lowercase English letters.
backtrackingstringdp
Open on LeetCode ↗
02

Intuition

Build each answer from left to right. The pieces chosen so far cover a prefix of s, and the next piece must start exactly where they stop. Try every palindrome that starts there, recurse on what is left, then take the piece back and try the next one. When the pieces reach the end of the string, they form one complete answer.

  • Pruning: a piece that is not a palindrome is skipped on the spot, so no branch ever holds a bad piece.
  • Constant-time checks: the same substring is tested in many branches, so a table pal[i][j] built once up front answers each test immediately.
How to spot this pattern

"Return all ways to split" or "list every partition" with a small input size points to backtracking: choose a piece, recurse on the rest, undo the choice.

03

Approach

Try it first

Before reading on, write down every split of "aab" by hand and notice where you first decide something. What is the next decision once the first piece is fixed? Aim for a search that never builds a split containing a non-palindrome.

1

Build the palindrome table

Set pal[i][j] to true when s[i] == s[j] and the part strictly between them is a palindrome (or there is nothing between them). Fill i from the end so that pal[i + 1][j - 1] is ready when it is read.

2

Choose the next piece

In dfs(start), loop end from start to the last index. When pal[start][end] is true, add s[start..end] to the current path. Only palindromes are ever added, so the path is always a valid partial answer.

3

Recurse on the rest of the string

Call dfs(end + 1). What remains is the same task on a shorter suffix, and the rules for it do not depend on how the prefix was cut.

4

Record a finished split

When start equals the length, the pieces cover the whole string. Append a copy of the path to the answers, because the path itself keeps changing as the search goes on.

5

Undo the choice

Remove the last piece after the recursive call returns. The loop then tries a longer piece from the same start, on top of the same prefix as before.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def partition(self, s: str) -> list[list[str]]:
▶3 n = len(s)
▶4 pal = [[False] * n for _ in range(n)]
▶5 for i in range(n - 1, -1, -1):
▶6 for j in range(i, n):
▶7 pal[i][j] = s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1])
▶8 res, path = [], []
▶9 
▶10 def dfs(start: int) -> None:
▶11 if start == n:
▶12 res.append(path[:])
▶13 return
▶14 for end in range(start, n):
▶15 if pal[start][end]:
▶16 path.append(s[start:end + 1])
▶17 dfs(end + 1)
▶18 path.pop()
▶19 
▶20 dfs(0)
▶21 return res
stringa0a1b2palindrome?012012yespathfound"b" is one letter → yes
i2
j2
pal[i][j]yes
A single letter reads the same both ways.
stringa0a1b2palindrome?01201yes2yespathfound"a" is one letter → yes
i1
j1
pal[i][j]yes
A single letter reads the same both ways.
stringa0a1b2palindrome?01201yesno2yespathfound"ab": ends differ → no
i1
j2
pal[i][j]no
The first and last letters differ, so the piece cannot read the same backwards, whatever lies between them.
stringa0a1b2palindrome?0120yes1yesno2yespathfound"a" is one letter → yes
i0
j0
pal[i][j]yes
A single letter reads the same both ways.
stringa0a1b2palindrome?0120yesyes1yesno2yespathfound"aa": two equal letters → yes
i0
j1
pal[i][j]yes
Two equal letters with nothing between them form a palindrome.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathfound"aab": ends differ → no
i0
j2
pal[i][j]no
The first and last letters differ, so the piece cannot read the same backwards, whatever lies between them.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathafoundtake "a" → split the rest, "ab"
start0
end0
path1 piece
"a" is a palindrome, so it becomes the next piece. What remains, "ab", is split by the same search, starting at index 1.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathaafoundtake "a" → split the rest, "b"
start1
end1
path2 pieces
"a" is a palindrome, so it becomes the next piece. What remains, "b", is split by the same search, starting at index 2.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathaabfoundtake "b" → nothing left
start2
end2
path3 pieces
"b" is a palindrome, so it becomes the next piece. It reaches the last letter, so the next call will find the string fully covered.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathaabfoundaabpieces reach the end → save a | a | b
start3
splits found1
The pieces now cover the whole string and each one is a palindrome, so this is a complete answer. A copy is saved, because the path will keep changing.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathaafoundaabremove "b" → no longer piece fits, back up
start2
path2 pieces
Every split that begins with the current pieces plus "b" has been listed. Taking "b" back ends this loop, since no longer piece can start at index 2, so the search returns to the previous piece.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathafoundaabremove "a" → try a longer piece from index 1
start1
path1 piece
Every split that begins with the current pieces plus "a" has been listed. Taking "a" back lets the loop try the next, longer piece that starts at index 1.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathafoundaab"ab" is not a palindrome → skip
start1
end2
The table says no for row 1, column 2. Any split starting with this piece would be invalid, so the whole branch is skipped without looking inside it.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathfoundaabremove "a" → try a longer piece from index 0
start0
path0 pieces
Every split that begins with the current pieces plus "a" has been listed. Taking "a" back lets the loop try the next, longer piece that starts at index 0.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathaafoundaabtake "aa" → split the rest, "b"
start0
end1
path1 piece
"aa" is a palindrome, so it becomes the next piece. What remains, "b", is split by the same search, starting at index 2.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathaabfoundaabtake "b" → nothing left
start2
end2
path2 pieces
"b" is a palindrome, so it becomes the next piece. It reaches the last letter, so the next call will find the string fully covered.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathaabfoundaabaabpieces reach the end → save aa | b
start3
splits found2
The pieces now cover the whole string and each one is a palindrome, so this is a complete answer. A copy is saved, because the path will keep changing.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathaafoundaabaabremove "b" → no longer piece fits, back up
start2
path1 piece
Every split that begins with the current pieces plus "b" has been listed. Taking "b" back ends this loop, since no longer piece can start at index 2, so the search returns to the previous piece.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathfoundaabaabremove "aa" → try a longer piece from index 0
start0
path0 pieces
Every split that begins with the current pieces plus "aa" has been listed. Taking "aa" back lets the loop try the next, longer piece that starts at index 0.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathfoundaabaab"aab" is not a palindrome → skip
start0
end2
The table says no for row 0, column 2. Any split starting with this piece would be invalid, so the whole branch is skipped without looking inside it.
stringa0a1b2palindrome?0120yesyesno1yesno2yespathfoundaabaabdone: 2 splits
return2 splits
Every piece that could start each split has been tried, so the found list holds every way to cut the string into palindromes.
05

Common pitfalls

Saving the path itself instead of a copy

✗ Wrong
res.append(path)
✓ Right
res.append(path[:])

Every saved entry is the same list object, and the undo steps empty it before the function returns. For s = "aab" the output becomes [[], []] instead of [["a", "a", "b"], ["aa", "b"]].

Filling the table from the front

✗ Wrong
for i in range(n):
✓ Right
for i in range(n - 1, -1, -1):

pal[i][j] reads pal[i + 1][j - 1], a row further down. Going from the front reads that row before it is filled. For s = "aba" the whole string looks like a non-palindrome and the answer ["aba"] goes missing.

06

Edge cases

A single letter

The only split is the letter itself, so the result is [[s]].

No palindrome longer than one letter, like "abc"

Every longer piece fails the table check, so the search walks straight down one branch and returns the single split into letters.

07

Complexity

Time
O(n · 2ⁿ)
Space
O(n²)
A string has 2ⁿ⁻¹ ways to place cuts, and in the worst case (all letters equal) every one is valid and copied in O(n). The table takes O(n²) time and space; the path and the recursion add O(n). The output is not counted.
08

Palindrome Partitioning FAQ

Do I need the table, or can I check each piece directly?

A two-pointer check on each piece also passes, since n is at most 16. It costs up to O(n) per check, and the same piece is checked again in every branch that reaches it. The table pays O(n²) once so that every later check is a lookup.

How is this different from Palindrome Partitioning II?

Palindrome Partitioning II asks only for the smallest number of cuts, not the splits themselves. That count can be found with an O(n²) table, so it allows strings of 2,000 letters, far beyond what listing every split could handle.