Algorithms · Visualized
Palindrome Partitioning
Backtracking
Build candidates incrementally and abandon ("prune") a branch the moment it can no longer lead to a valid answer.
Splits a string into all possible groups of substrings where every substring in the group is itself a palindrome. Time: O(n × 2ⁿ) average, O(n × 2ⁿ) — up to 2ⁿ possible partitions worst; space: O(n) recursion depth.
Big-O: Try a choice, recurse, undo it, try the next. Depth-first search over the space of partial solutions.
Palindrome Partitioning
BacktrackingSplits a string into all possible groups of substrings where every substring in the group is itself a palindrome. Backtracking tries every possible 'cut point': if the piece from the start to the cut is a palindrome, recurse on the rest of the string; otherwise try a longer piece.
How Palindrome Partitioning Works
- Start at position 0 with an empty current partition list.
- From the current position, try every possible ending point for the next piece.
- Check if the substring from the current position to that ending point is a palindrome.
- If it is, add it to the current partition and recursively partition the remainder of the string starting right after it.
- When the current position reaches the end of the string, the current partition is a complete valid answer — record it, then backtrack to try other cut points.
Palindrome Partitioning Worked Example
Input: aab
From pos0: try 'a' (palindrome) → recurse from pos1. From pos1: try 'a' (palindrome) → recurse from pos2: try 'b' (palindrome) → reached end, record ['a','a','b']. Backtrack; from pos1 try 'ab' (not palindrome, skip). Backtrack to pos0; try 'aa' (palindrome) → recurse from pos2: 'b' palindrome → record ['aa','b']. Result: [['a','a','b'], ['aa','b']].
def palindrome_partitioning(s):
out = []
def build(i, cur):
if i == len(s):
out.append(cur[:])
return
for j in range(i, len(s)):
part = s[i:j + 1]
if part == part[::-1]:
cur.append(part)
build(j + 1, cur)
cur.pop()
build(0, [])
return outBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Palindrome Partitioning Time & Space Complexity
When to Use Palindrome Partitioning
- DNA sequence analysis for palindromic segments, and text processing tasks needing all valid palindrome splits.
- Building block for the more optimized DP-based 'minimum cuts for palindrome partitioning' problem.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.