oneby7

2-D Dynamic Programming Two strings

568. Minimum Insertion Steps to Make a String Palindrome

Hard

You are given a string s. In one step you may insert any lowercase letter at any position of s: at the start, at the end, or between two letters. Return the fewest steps that turn s into a palindrome.

A palindrome reads the same forwards and backwards, such as "noon" or "refer". The letters already in s stay in their order, and none can be removed.

Example 1

Input: s = "genie"

Output: 2

Explanation: Insert an n after the i and a g at the end. That gives genineg, which reads the same both ways. One insertion is not enough.

Example 2

Input: s = "kayak"

Output: 0

Explanation: The string is already a palindrome, so no step is needed.

Example 3

Input: s = "dog"

Output: 2

Explanation: No letter repeats, so only one letter can stay unpaired in the middle. dogod adds a partner for the d and for the o.

Check your understanding

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

s = "worrier"

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.