๐๏ธ Day 38: Palindrome Partitioning โ All Ways to Split
๐ง Concept Deep Dive
Given a string s, partition it so that every substring in the partition is a palindrome. Return all possible palindrome partitioning of s.
This is a classic Backtracking + Dynamic Programming (pruning) problem. We try all ways to split the string, but we only proceed with a split if the substring is a palindrome.
๐ฏ Visual Intuition
For s = "aab", the possible partitions are:
[
["a", "a", "b"], // all single-character palindromes
["aa", "b"] // "aa" is a palindrome
]We move character by character, try slicing the string from the start to i, and recursively explore the rest โ but only if the current slice is a palindrome.
๐ ๏ธ Code Pattern: Backtracking with Palindrome Check
function partition(s: string): string[][] {
const res: string[][] = [];
function isPalindrome(str: string, l: number, r: number): boolean {
while (l < r) {
if (str[l] !== str[r]) return false;
l++;
r--;
}
return true;
}
function backtrack(start: number, path: string[]) {
if (start === s.length) {
res.push([...path]);
return;
}
for (let end = start; end < s.length; end++) {
if (isPalindrome(s, start, end)) {
path.push(s.slice(start, end + 1));
backtrack(end + 1, path);
path.pop();
}
}
}
backtrack(0, []);
return res;
}๐ Example
Input: "aab"
Output:
[
["a", "a", "b"],
["aa", "b"]
]
Input: "a"
Output:
[
["a"]
]๐งช Homework
- What if the input string is empty?
- Count the number of valid palindrome partitions.
- Optimize palindrome checking with DP memoization.
๐ง Big-O Cheat Sheet
- Time:
O(N * 2^N)โ exploring all partitions and checking for palindrome - Space:
O(N)recursion depth + result list size
๐ฎ Up Next
โถ๏ธ Day 39: DP + Backtracking โ Palindrome Partitioning II (Min Cuts)