You are given a string s. Cut it into one or more consecutive pieces so that every piece is a palindrome: it reads the same forwards and backwards.
Return every way to do this. Each way is a list of the pieces in order, and the ways themselves may come back in any order.
Example 1
Input: s = "abb" Output: [["a","b","b"], ["a","bb"]] Why: "ab" and "abb" are not palindromes, so "a" must stand alone
2 more examples and the constraints
Example 2
Input: s = "z" Output: [["z"]] Why: one letter is one palindrome
Example 3
Input: s = "aba" Output: [["a","b","a"], ["aba"]] Why: the whole string is also a palindrome
Constraints
- 1 ≤ length of s ≤ 16
sholds only lower-case English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every set of cutsO(n·2ⁿ)
- BacktrackingO(n·2ⁿ)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 16 mixed letters | Verdict |
|---|---|---|---|
| Try every set of cuts | O(n·2ⁿ) | Works; checks dead patterns in full | |
| Backtracking | O(n·2ⁿ) | Best; drops bad prefixes early |
n = length of s. Both are O(n·2ⁿ) when every letter is the same, because then that many answers exist.
Edge cases to test
- One letter. "z" has exactly one answer: [["z"]].
- All letters the same. "aaaa" has 8 answers: every set of cuts works.
- No two letters match. "abc" has one answer, every letter alone.
- The whole string is a palindrome. "aba" must include ["aba"] as one of its answers.
Common mistakes
- Saving
pathitself instead of a copy, so every saved answer ends up empty after the pops. - Forgetting to pop after the recursive call, so pieces from one branch leak into the next.
- Stopping at the first answer found instead of collecting all of them.
How to talk through it
- 1Clarify. Do I return every partition or just a count? Does one letter count as a palindrome? Does the order of answers matter?
- 2Count the options. n − 1 gaps, cut or not: 2ⁿ⁻¹ patterns, small enough for 16 letters.
- 3Prune with backtracking. Choose the first piece, only if it is a palindrome, and recurse on the rest.
- 4Code it. Push, recurse, pop. Copy the path when you reach the end.
- 5Test out loud. Run "z", "aaaa" and "abc" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?