You are given a string s. Cut it into pieces so that every piece reads the same forwards and backwards (a palindrome).
Return the smallest number of cuts that makes this possible. A string that is already a palindrome needs 0 cuts.
Example 1
Input: s = "abab" Output: 1 Why: "aba" | "b", or "a" | "bab"
2 more examples and the constraints
Example 2
Input: s = "racecar" Output: 0 Why: the whole string is a palindrome
Example 3
Input: s = "abcd" Output: 3 Why: no two letters match, so each one is its own piece
Constraints
- 1 ≤ length of s ≤ 2,000
- s has only lowercase English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- DP, check each pieceO(n³)
- Grow from centresO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 2,000 letters | Verdict |
|---|---|---|---|
| DP, check each piece | O(n³) | Correct, but too slow | |
| Grow from centres | O(n²) | Best; no extra table |
n = length of s.
Edge cases to test
- Already a palindrome. "racecar" needs 0 cuts. cuts[0] = −1 is what makes this come out as 0.
- One letter. "z" is a palindrome: 0.
- No letters match. "abcd" needs n − 1 = 3 cuts, the starting value.
- Even-length palindromes. "xabbay" has "abba" in the middle. Skip the even centres and you get 3 instead of 2.
Common mistakes
- Greedily taking the longest palindrome from the left: "aaabaa" becomes "aaa" | "b" | "aa" (2 cuts), but "a" | "aabaa" needs only 1.
- Only growing odd centres, so palindromes like "abba" are never found.
- Starting cuts[0] at 0 instead of −1, so every answer comes out one too high.
How to talk through it
- 1Clarify. Do we return the number of cuts or pieces? Is a single letter a palindrome? How long can s be?
- 2Set up the DP. cuts[i] is the fewest cuts for the first i letters; try every palindrome that can be the last piece.
- 3Find the slow part. Testing each piece from scratch makes it O(n³). We need every palindrome in O(1) each.
- 4Grow from centres. Expanding around each centre lists all palindromes in O(n²) total; update cuts[hi + 1] from cuts[lo] as you go.
- 5Test out loud. Run "abab", a full palindrome, and a string with an even palindrome like "xabbay".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?