Algorithm Day62 - Palindrome Partitioning
🧩 Problem Description
Given a string s
, partition s
such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s
.
💬 Example
Example 1
1 | Input: s = "aab" |
Example 2
1 | Input: s = "a" |
💡 Intuition
We need to explore all possible partitions of the string and check if each substring is a palindrome.
This is a classic backtracking problem:
- Start from index
0
. - Expand substring
[start..i]
. - If it is a palindrome, recursively partition the rest.
- Collect valid partitions when we reach the end.
🔢 Java Code (Backtracking)
1 | import java.util.*; |
⏱ Complexity Analysis
Let n = s.length()
.
- Time: O(n × 2^n) — because each index can start a new partition cut, and palindrome check takes O(n).
- Space: O(n) recursion depth + O(n) for substring storage.
✍️ Summary
- Use backtracking to explore all partitions.
- Only continue recursion if substring is a palindrome.
- Collect valid partitions when reaching the end.
Related problems
lc-132
— Palindrome Partitioning II (min cuts)lc-647
— Palindromic Substringslc-5
— Longest Palindromic Substring