Given a string, find the minimum number of characters to be inserted to convert it to palindrome.
Before we go further, let us understand with few examples:
ab: Number of insertions required is 1. bab
aa: Number of insertions required is 0. aa
abcd: Number of insertions required is 3. dcbabcd
abcda: Number of insertions required is 2. adcbcda which is same as number of insertions in the substring bcd(Why?).
abcde: Number of insertions required is 4. edcbabcde
Let the input string be str[l……h]. The problem can be broken down into three parts:
1. Find the minimum number of insertions in the substring str[l+1,…….h].
2. Find the minimum number of insertions in the substring str[l…….h-1].
3. Find the minimum number of insertions in the substring str[l+1……h-1].
Recursive Solution
The minimum number of insertions in the string str[l…..h] can be given as:
minInsertions(str[l+1…..h-1]) if str[l] is equal to str[h]
min(minInsertions(str[l…..h-1]), minInsertions(str[l+1…..h])) + 1 otherwise
Dynamic Programming based Solution
If we observe the above approach carefully, we can find that it exhibits overlapping subproblems.
Suppose we want to find the minimum number of insertions in string “abcde”:
abcde / | \ / | \ bcde abcd bcd <- case 3 is discarded as str[l] != str[h] / | \ / | \ / | \ / | \ cde bcd cd bcd abc bc / | \ / | \ /|\ / | \ de cd d cd bc c………………….
The substrings in bold show that the recursion to be terminated and the recursion tree cannot originate from there. Substring in the same color indicates overlapping subproblems.
How to reuse solutions of subproblems?
We can create a table to store results of subproblems so that they can be used directly if same subproblem is encountered again.
The below table represents the stored values for the string abcde.
a b c d e
----------
0 1 2 3 4
0 0 1 2 3
0 0 0 1 2
0 0 0 0 1
0 0 0 0 0
How to fill the table?
The table should be filled in diagonal fashion. For the string abcde, 0….4, the following should be order in which the table is filled:
Gap = 1: (0, 1) (1, 2) (2, 3) (3, 4) Gap = 2: (0, 2) (1, 3) (2, 4) Gap = 3: (0, 3) (1, 4) Gap = 4: (0, 4)
Another Dynamic Programming Solution (Variation of Longest
Common Subsequence Problem)
The problem of finding minimum insertions can also be solved using Longest Common Subsequence (LCS) Problem. If we find out LCS of string and its reverse, we
know how many maximum characters can form a palindrome. We need insert remaining characters. Following are the steps.
1) Find the length of LCS of input string and its reverse. Let the length be ‘l’.
2) The minimum number insertions needed is length of input string minus ‘l’.
package DP; public class MinInsertionsPalindrome { public static void main(String[] args) { String s = "geeks"; int l = 0; int h = s.length()-1; System.out.println(findMinInsertionsRec(s, l, h)); System.out.println(findMinInsertionsDP(s, s.length())); System.out.println(findMinInsertionsLCS(s, s.length())); } public static int findMinInsertionsRec(String s, int l, int h){ if(l > h){ return Integer.MAX_VALUE; } if(l == h){ return 0; } if(l+1 == h){ return (s.charAt(l)==s.charAt(h) ? 0 : 1); } if(s.charAt(l) == s.charAt(h)){ return findMinInsertionsRec(s, l+1, h-1); }else{ return Math.min(findMinInsertionsRec(s, l+1, h), findMinInsertionsRec(s, l, h-1)) + 1; } } // Time complexity: O(N^2) Auxiliary Space: O(N^2) public static int findMinInsertionsDP(String s, int n){ int[][] dp = new int[n][n]; for(int gap=1; gap<n; gap++){ // gap: l到h之间的距离 int l = 0, h = gap; while(h < n){ // 平行移动l...h if(s.charAt(l) == s.charAt(h)){ dp[l][h] = dp[l+1][h-1]; }else{ dp[l][h] = Math.min(dp[l+1][h], dp[l][h-1]) + 1; } l++; h++; } } return dp[0][n-1]; } // Time complexity: O(N^2) Auxiliary Space: O(N^2) public static int findMinInsertionsLCS(String s, int n){ // Create another string to store reverse of 'str' String rev = new StringBuilder(s).reverse().toString(); // The output is length of string minus length of lcs of // str and it reverse return n - lcs(s, rev, n, n); } /* Returns length of LCS for X[0..m-1], Y[0..n-1]. See http://goo.gl/bHQVP for details of this function */ public static int lcs(String X, String Y, int m, int n){ int[][] L = new int[m+1][n+1]; /* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */ for(int i=0; i<=m; i++){ for(int j=0; j<=n; j++){ if(i==0 || j==0){ // 空string L[i][j] = 0; }else if(X.charAt(i-1) == Y.charAt(j-1)){ // 最后一位相同 L[i][j] = L[i-1][j-1] + 1; // 比较前面的位数 }else{ // 最后一位不同 L[i][j] = Math.max(L[i-1][j], L[i][j-1]); } } } return L[m][n]; /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */ } }