Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The fewest cuts into palindromes

Hard · Target 25 minutes · Dynamic programming · Type asked atGoogleAmazon

Given a string s, cut it into pieces so that every piece is a palindrome. Return the smallest number of cuts needed. A string that is already a palindrome needs 0 cuts.

Examples

InputOutputWhy
s = "aab"1"aa" | "b".
s = "aabcbd"2"aa" | "bcb" | "d".
s = "racecar"0Already a palindrome.

Constraints

  • 1 ≤ s.length ≤ 2000
  • Lowercase English letters

Hints

Hint 1

Precompute pal[j][i]: is s[j..i] a palindrome? It is when s[j] = s[i] and the inside is.

Hint 2

Let cuts[i] be the fewest cuts for s[0..i]. The last piece is some palindrome s[j..i].

Hint 3

cuts[i] = 0 if s[0..i] is a palindrome, otherwise min over j ≥ 1 with pal[j][i] of cuts[j − 1] + 1.

Where people lose marks

  • Testing each candidate piece for being a palindrome from scratch, which makes it O(n³).
  • Counting pieces instead of cuts (off by one).
  • Greedily taking the longest palindrome first: "aabaa" + "b" style strings defeat it.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.