All problems

Problem 292

Minimum Insertions to Make Palindrome

Hard · 30 pts · String, Dynamic Programming

Problem

You are given a string S. In one step you may insert any character at any position. Find the minimum number of insertions needed to turn S into a palindrome, a string that reads the same forwards and backwards. The characters you keep without a partner must already form a palindrome, so the answer is |S| minus the length of the longest palindromic subsequence of S. You can compute it with an interval DP, or as the longest common subsequence of S and its reverse.

Input

A single string S of lowercase letters.

Output

Print the minimum number of insertions.

Constraints

1 <= |S| <= 500

Example input

mbadm

Example output

2

Explanation

The longest palindromic subsequence of "mbadm" has length 3 (for example "mam"), so 5 - 3 = 2 insertions are needed. One way is to insert b and d to get "mbdadbm".

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Paint House Next: Target Sum