Palindrome Partitioning
Pattern: Palindrome partitioning
Cut the string from the left. At each position, try every next piece that is a palindrome, recurse on the rest, and undo. When the cuts reach the end, record the pieces.
Solve on LeetCodeSolve on GeeksforGeeks
The problem
Given a string, return every way to split it into pieces such that every piece is a palindrome. For example, "aab"
gives [a, a, b] and [aa, b], and "a" gives [a].
The function name partition matches LeetCode. Use the link above for the exact statement and limits. Any order is
accepted, so the tests sort the list of partitions. The GFG link covers the same problem.
Think first
- What choice is made at each step?
- Which choices can be ruled out at once?
- When is a partition complete?
Hints
Brute force, and why it fails
Try all 2^(n-1) ways to cut, then check every piece. Checking each piece as it is chosen prunes most of those.
The key insight
A partition is a sequence of cut choices from left to right. Rejecting non-palindromic pieces at the moment they are chosen removes whole subtrees.
Dry run
| parts |
|---|
s = aab. The first piece can be a or aa (aab is not a palindrome).
The plan
function cut(start, parts):
if start == n: record a copy of parts; return
for end from start + 1 to n:
piece = s[start .. end - 1]
if piece is a palindrome:
add piece; cut(end, parts); remove it
cut(0, [])
Complexity
- Time
O(2ⁿ × n)- Space
O(n)
Up to 2^(n-1) partitions, each with O(n) checking and copying. The recursion is n deep.
Edge cases
- One character: one partition.
- All equal, as in
"aaa": four partitions. - No two equal neighbours: only single letters, one partition.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<String>> partition(String s) {
List<List<String>> out = new ArrayList<>();
cut(s, 0, new ArrayList<>(), out);
return out;
}
private void cut(String s, int start, List<String> parts, List<List<String>> out) {
if (start == s.length()) { out.add(new ArrayList<>(parts)); return; } // the whole string is cut up
for (int end = start + 1; end <= s.length(); end++) {
if (!isPal(s, start, end - 1)) continue; // the next piece must be a palindrome
parts.add(s.substring(start, end));
cut(s, end, parts, out);
parts.remove(parts.size() - 1);
}
}
private boolean isPal(String s, int l, int r) {
while (l < r) if (s.charAt(l++) != s.charAt(r--)) return false;
return true;
}
}C++
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> out;
vector<string> parts;
cut(s, 0, parts, out);
return out;
}
void cut(const string& s, size_t start, vector<string>& parts, vector<vector<string>>& out) {
if (start == s.size()) { out.push_back(parts); return; } // the whole string is cut up
for (size_t end = start + 1; end <= s.size(); end++) {
if (!isPal(s, start, end - 1)) continue; // the next piece must be a palindrome
parts.push_back(s.substr(start, end - start));
cut(s, end, parts, out);
parts.pop_back();
}
}
bool isPal(const string& s, size_t l, size_t r) {
while (l < r) if (s[l++] != s[r--]) return false;
return true;
}
};Python
class Solution:
def partition(self, s: str) -> list[list[str]]:
out = []
def cut(start: int, parts: list) -> None:
if start == len(s):
out.append(parts[:]) # the whole string is cut up
return
for end in range(start + 1, len(s) + 1):
piece = s[start:end]
if piece == piece[::-1]: # the next piece must be a palindrome
parts.append(piece)
cut(end, parts)
parts.pop()
cut(0, [])
return outCommon mistakes
- Recording
partswithout copying it. - Checking palindromes only at the end.
- Using
endas an inclusive index in one place and exclusive in another.