Given string str, the task is to find the minimum number of characters to be inserted to convert it to a palindrome.
Before we go further, let us understand with a few examples:
- ab: Number of insertions required is 1 i.e. bab
- aa: Number of insertions required is 0 i.e. aa
- abcd: Number of insertions required is 3 i.e. dcbabcd
- abcda: Number of insertions required is 2 i.e. adcbcda which is the same as the number of insertions in the substring bcd(Why?).
- abcde: Number of insertions required is 4 i.e. edcbabcde
Let the input string be str[l……h]. The problem can be broken down into three parts:
- Find the minimum number of insertions in the substring str[l+1,…….h].
- Find the minimum number of insertions in the substring str[l…….h-1].
- Find the minimum number of insertions in the substring str[l+1……h-1].
Recursive Approach: 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
Below is the implementation of the above approach:
Java
class GFG
{
static int findMinInsertions( char str[],
int l, int h)
{
if (l > h)
return Integer.MAX_VALUE;
if (l == h)
return 0 ;
if (l == h - 1 )
return (str[l] == str[h]) ? 0 : 1 ;
return (str[l] == str[h])?
findMinInsertions(str, l + 1 , h - 1 ):
(Integer.min(findMinInsertions(str, l, h - 1 ),
findMinInsertions(str, l + 1 , h)) + 1 );
}
public static void main(String args[])
{
String str= "geeks" ;
System.out.println(
findMinInsertions(str.toCharArray(),
0 , str.length()- 1 ));
}
}
|
Output:
3
Time Complexity: O(2^n), where n is the length of the input string. This is because for each recursive call, there are two possibilities: either we insert a character at the beginning of the string or at the end of the string. Therefore, the total number of recursive calls made is equal to the number of binary strings of length n, which is 2^n.
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 is to be terminated and the recursion tree cannot originate from there. Substring in the same color indicates overlapping subproblems.
How to re-use solutions of subproblems? The memorization technique is used to avoid similar subproblem recalls. We can create a table to store the results of subproblems so that they can be used directly if the 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 a diagonal fashion. For the string abcde, 0….4, the following should be ordered 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)
Below is the implementation of the above approach:
Java
import java.util.Arrays;
class GFG
{
static int findMinInsertionsDP( char str[],
int n)
{
int table[][] = new int [n][n];
int l, h, gap;
for (gap = 1 ; gap < n; ++gap)
for (l = 0 , h = gap; h < n; ++l, ++h)
table[l][h] = (str[l] == str[h])?
table[l+ 1 ][h- 1 ] :
(Integer.min(table[l][h- 1 ],
table[l+ 1 ][h]) + 1 );
return table[ 0 ][n- 1 ];
}
public static void main(String args[])
{
String str = "geeks" ;
System.out.println(
findMinInsertionsDP(str.toCharArray(),
str.length()));
}
}
|
Output:
3
Time complexity: O(N^2)
Auxiliary Space: O(N^2)
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 the LCS of string and its reverse, we know how many maximum characters can form a palindrome. We need to insert the remaining characters. Following are the steps.
- Find the length of LCS of the input string and its reverse. Let the length be ‘l’.
- The minimum number of insertions needed is the length of the input string minus ‘l’.
Below is the implementation of the above approach:
Java
class GFG
{
static int lcs(String X, String Y,
int m, int n)
{
int L[][] = new int [m+ 1 ][n+ 1 ];
int i, j;
for (i = 0 ; i <= m; i++)
{
for (j = 0 ; j <= n; j++)
{
if (i == 0 || j == 0 )
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] = Integer.max(L[i- 1 ][j],
L[i][j- 1 ]);
}
}
return L[m][n];
}
static int findMinInsertionsLCS(String str,
int n)
{
StringBuffer sb = new StringBuffer(str);
sb.reverse();
String revString = sb.toString();
return (n - lcs(str, revString , n, n));
}
public static void main(String args[])
{
String str = "geeks" ;
System.out.println(
findMinInsertionsLCS(str, str.length()));
}
}
|
Output:
3
Time complexity: O(N^2)
Auxiliary Space: O(N^2)
Please refer complete article on Minimum insertions to form a palindrome | DP-28 for more details!
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!