Palindrome Partitioning
Difficulty: Medium · Pattern: Backtracking · LeetCode #131
Partition s so that every substring of the partition is a palindrome. Return all possible partitions, in any order.
Examples
text
"aab" → [["a","a","b"],["aa","b"]]
"a" → [["a"]]Hints
- Choose the first piece
s[0..end]. It must be a palindrome. Then partition the rest the same way. - Checking palindromes repeatedly is wasteful. Precompute
pal[i][j]with DP:s[i]==s[j] and pal[i+1][j-1].
Approach
- DP table: fill
pal[i][j]for i from n−1 down to 0, sopal[i+1][j−1]is ready when you need it. That's O(n²). - Backtrack:
bt(start): ifstart == n, record the path. Otherwise for eachend ≥ startwithpal[start][end], pushs[start:end+1], recurse onend+1, and pop.
There can be up to 2ⁿ⁻¹ partitions (for "aaaa…"), so the output dominates: O(n · 2ⁿ).
Complexity
Time: O(n · 2ⁿ). Space: O(n²) for the table.
Python solution
def partition(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):
pal[i][j] = s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1])
res, path = [], []
def bt(start):
if start == n:
res.append(path[:])
return
for end in range(start, n):
if pal[start][end]:
path.append(s[start:end + 1])
bt(end + 1)
path.pop()
bt(0)
return resJavaScript solution
function partition(s) {
const n = s.length, pal = Array.from({ length: n }, () => new Array(n).fill(false));
for (let i = n - 1; i >= 0; i--) for (let j = i; j < n; j++) pal[i][j] = s[i] === s[j] && (j - i < 2 || pal[i + 1][j - 1]);
const res = [], path = [];
const bt = (start) => {
if (start === n) { res.push([...path]); return; }
for (let end = start; end < n; end++) if (pal[start][end]) { path.push(s.slice(start, end + 1)); bt(end + 1); path.pop(); }
};
bt(0);
return res;
}