Given a string s, split s into substrings where every substring is a palindrome. Return all possible lists of palindromic substrings.
1 ≤ s.length ≤ 20s contains only lowercase English letters.Before attempting this problem, you should be comfortable with:
We build the partition from left to right. At any starting index i, we have a simple question: "Where should I cut next?"
So we try every possible end index j from i to the end. If s[i..j] is a palindrome, it can be the next piece. We choose it (add to our current partition), then recursively solve the rest starting at j + 1. After returning, we undo the choice and try a different j.
Maintain: part: current list of chosen substrings. res: all palindrome partitions. Define DFS dfs(i) where i is the start index of the next substring. Base case: If i == len(s), the whole string has been partitioned → add a copy of part to res. For each j from i to len(s)-1: If s[i..j] is palindrome: Add s[i..j] to part. Recurse dfs(j + 1). Backtrack: remove last substring. Palindrome check: Two pointers l, r move inward; if mismatch → return false.Time Complexity: O(N × 2N) where N is the length of the string. In the worst case (e.g., all identical characters), there are 2N-1 possible partitions, and each takes O(N) to check and build.
Space Complexity: O(N) for the recursion stack and the current partition list.
Watch the algorithm drop a "knife" to slice the string. After each cut, it sends two pointers to verify if the sliced substring is a palindrome. If it is, the chunk is added to the Current Partition and recursion continues.
When adding the current partition to the results list, you must add a copy of the list, not a reference to it. Since backtracking modifies the same partition list, adding the reference directly means all entries in the result will point to the same (eventually empty) list.
The base case should trigger when the starting index reaches the end of the string, indicating a complete valid partition. A common mistake is to check i > len(s) instead of i >= len(s) or i == len(s), causing missed partitions or index errors.
Discussion
…