Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Dynamic Programming

Minimum Insertions to Make a Palindrome

Medium · Dynamic Programming · Asked at Amazon, Google, Microsoft, Adobe

Print the minimum number of characters you must insert (anywhere) into s to make it a palindrome.

Input

A single line with the string s.

Output

The minimum number of insertions.

Constraints

The characters that already pair up form the longest palindromic subsequence; every other character needs a partner inserted. Answer = n − LPS(s), and LPS(s) = LCS(s, reverse(s)).

Example 1

Input

zzazz

Output

0

Example 2

Input

mbadm

Output

2

Hints

  1. Characters that can stay paired already form a palindromic subsequence.
  2. Keep the longest one; every other character needs one inserted partner.
  3. The longest palindromic subsequence of s is the LCS of s and its reverse.

Approach

Compute L = LCS(s, reverse(s)) with the usual table (one row at a time is enough), which equals the longest palindromic subsequence. The answer is |s| − L: each unmatched character gets a mirror copy inserted on the other side.

Complexity: O(n²) time · O(n) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    string s;
    cin >> s;
    string t(s.rbegin(), s.rend());
    int n = s.size();
    vector<int> prev(n + 1, 0), cur(n + 1, 0);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) cur[j] = s[i - 1] == t[j - 1] ? prev[j - 1] + 1 : max(prev[j], cur[j - 1]);
        swap(prev, cur);
    }
    cout << n - prev[n] << "\n";
    return 0;
}

Python solution

s = input().strip()
t = s[::-1]
n = len(s)
prev = [0] * (n + 1)
for i in range(1, n + 1):
    cur = [0] * (n + 1)
    si = s[i - 1]
    for j in range(1, n + 1):
        if si == t[j - 1]:
            cur[j] = prev[j - 1] + 1
        else:
            cur[j] = prev[j] if prev[j] > cur[j - 1] else cur[j - 1]
    prev = cur
print(n - prev[n])

Java solution

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
        String t = new StringBuilder(s).reverse().toString();
        int n = s.length();
        int[] prev = new int[n + 1], cur = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) cur[j] = s.charAt(i - 1) == t.charAt(j - 1) ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
            int[] tmp = prev;
            prev = cur;
            cur = tmp;
        }
        System.out.println(n - prev[n]);
    }
}

Solve Minimum Insertions to Make a Palindrome online · All practice problems