Minimum Insertions to Make String Palindrome

Hard · Dynamic Programming · String · Dynamic Programming

Problem

Given a string s, one step inserts any character at any position.

Return the minimum number of steps needed to turn s into a palindrome (a string that reads the same forwards and backwards).

Examples

Input: s = "abcb"
Output: 1

Append "a" to get "abcba".

Input: s = "race"
Output: 3

No two letters can face each other, so three of the four need a mirror: "ecarace".

Input: s = "noon"
Output: 0

Already a palindrome.

Constraints

Approaches

Follow-up

The same table answers "fewest deletions to make a palindrome" (it is the same number). The use cases restrict insertions to the front (then only a palindromic prefix can stay, found in linear time) and put a price on each inserted letter.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…