Problem
Section titled “Problem”Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.
Example 1:
Input: s = "aab"Output: [["a","a","b"],["aa","b"]]Example 2:
Input: s = "a"Output: [["a"]]Constraints:
-
s.length scontains only lowercase English letters.
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”A partition is decided left to right: choose the first piece s[0..j], then partition the rest s[j+1..] the same way. Only palindromic first pieces are allowed, so at each position we try every end j for which s[start..j] is a palindrome, recurse, and undo the choice afterwards (backtracking). Every path that reaches the end of the string is one valid partition, and every valid partition is reached by exactly one path, so nothing is missed or duplicated.
Checking “is s[start..j] a palindrome?” by reversing the substring costs each time. Precompute it instead: pal[i][j] is true when s[i] == s[j] and the inside s[i+1..j-1] is a palindrome (or has length at most 1). Filling i from right to left guarantees pal[i+1][j-1] is ready. Each check is then .
Algorithm
Section titled “Algorithm”- Let
n = s.size(). Fillpal[i][j]forifromn - 1down to0andjfromiton - 1:pal[i][j] = s[i] == s[j] && (j - i < 2 || pal[i + 1][j - 1]). dfs(start): ifstart == n, append the current piecescurtoresultand return.- Otherwise, for each
jfromstartton - 1withpal[start][j], pushs.substr(start, j - start + 1)ontocur, calldfs(j + 1), then pop it. - Call
dfs(0)and returnresult.
Walkthrough
Section titled “Walkthrough”The recursion tree for s = "aab". Each edge is a palindromic piece cut from the front; red leaves are prefixes that are not palindromes (never explored), green leaves are complete partitions:
Complexity
Section titled “Complexity”- Time: — there are gaps, each cut or not, so at most partitions; building each one copies at most characters. The table costs . A string like
"aaaa…a"really has partitions, so no algorithm can do better in the worst case. - Space: for
pal, plus for the recursion andcur(not counting the output).
Edge cases
Section titled “Edge cases”- Single character (Example 2):
pal[0][0]is true, so the only partition is["a"]. - All characters equal: every substring is a palindrome, giving the maximum partitions; the table keeps each check .
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { vector<vector<bool>> pal; vector<string> cur; vector<vector<string>> result;
void dfs(const string& s, int start) { int n = s.size(); if (start == n) { result.push_back(cur); return; } for (int j = start; j < n; j++) { if (!pal[start][j]) continue; cur.push_back(s.substr(start, j - start + 1)); dfs(s, j + 1); cur.pop_back(); } }
public: vector<vector<string>> partition(string s) { int n = s.size(); pal.assign(n, vector<bool>(n, false)); for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { pal[i][j] = s[i] == s[j] && (j - i < 2 || pal[i + 1][j - 1]); } } dfs(s, 0); return result; }};class Solution { private boolean[][] pal; private final List<String> cur = new ArrayList<>(); private final List<List<String>> result = new ArrayList<>();
private void dfs(String s, int start) { int n = s.length(); if (start == n) { result.add(new ArrayList<>(cur)); return; } for (int j = start; j < n; j++) { if (!pal[start][j]) continue; cur.add(s.substring(start, j + 1)); dfs(s, j + 1); cur.remove(cur.size() - 1); } }
public List<List<String>> partition(String s) { int n = s.length(); pal = new boolean[n][n]; for (int i = n - 1; i >= 0; i--) { for (int j = i; j < n; j++) { pal[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 2 || pal[i + 1][j - 1]); } } dfs(s, 0); return result; }}class Solution: def partition(self, s: str) -> list[list[str]]: 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])
result, cur = [], []
def dfs(start: int) -> None: if start == n: result.append(cur[:]) return for j in range(start, n): if not pal[start][j]: continue cur.append(s[start:j + 1]) dfs(j + 1) cur.pop()
dfs(0) return resultGive it a try first
Attempt the problem on LeetCode — the code will still be here.
![Recursion tree for aab: palindromic cuts lead to [a, a, b] and [aa, b]; ab and aab are pruned](/CodePrime/img/codes/palindrome-partitioning/recursion-tree.png)