oneby7

2-D Dynamic Programming Splitting a range

573. Palindrome Partitioning II

Hard

You are given a string s of lowercase letters. Cut s into pieces so that every piece is a palindrome, and return the fewest cuts that do it.

A palindrome reads the same from left to right as from right to left, like "level", "noon" or a single letter. A cut goes between two neighbouring letters, so k cuts split s into k + 1 pieces.

A single letter is always a palindrome, so cutting between every pair of letters always works. If s is a palindrome already, it needs no cut at all, and the answer is 0.

Example 1

Input: s = "racecarannakayak"

Output: 2

Explanation: Cut after "racecar" and after "anna". The three pieces "racecar", "anna" and "kayak" are all palindromes. No single cut works, because no way of splitting s in two gives two palindromes.

Example 2

Input: s = "abcde"

Output: 4

Explanation: No piece longer than one letter is a palindrome, so every letter is a piece of its own. Five pieces need four cuts.

Example 3

Input: s = "q"

Output: 0

Explanation: A single letter is already a palindrome, so no cut is needed.

Check your understanding

Work out the answer for this input before you write any code.

s = "level"

Constraints

  • 1 ≤ s.length ≤ 3000
  • s holds only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.