Minimum insertions to form a palindrome | DP-28
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:
C++
#include<bits/stdc++.h>
using namespace std;
int findMinInsertions( char str[], int l, int h)
{
if (l > h) return INT_MAX;
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):
(min(findMinInsertions(str, l, h - 1),
findMinInsertions(str, l + 1, h)) + 1);
}
int main()
{
char str[] = "geeks" ;
cout << findMinInsertions(str, 0, strlen (str) - 1);
return 0;
}
|
C
#include <stdio.h>
#include <limits.h>
#include <string.h>
int min( int a, int b)
{ return a < b ? a : b; }
int findMinInsertions( char str[], int l, int h)
{
if (l > h) return INT_MAX;
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):
(min(findMinInsertions(str, l, h - 1),
findMinInsertions(str, l + 1, h)) + 1);
}
int main()
{
char str[] = "geeks" ;
printf ( "%d" , findMinInsertions(str, 0, strlen (str)-1));
return 0;
}
|
Java
import java.util.*;
import java.io.*;
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 ));
}
}
|
Python 3
import sys
def findMinInsertions( str , l, h):
if (l > h):
return sys.maxsize
if (l = = h):
return 0
if (l = = h - 1 ):
return 0 if ( str [l] = = str [h]) else 1
if ( str [l] = = str [h]):
return findMinInsertions( str , l + 1 , h - 1 )
else :
return ( min (findMinInsertions( str , l, h - 1 ),
findMinInsertions( str , l + 1 , h)) + 1 )
if __name__ = = "__main__" :
str = "geeks"
print (findMinInsertions( str , 0 , len ( str ) - 1 ))
|
C#
using System;
class GFG
{
static int findMinInsertions( char []str,
int l, int h)
{
if (l > h) return int .MaxValue;
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):
(Math.Min(findMinInsertions(str, l,
h - 1),
findMinInsertions(str, l +
1, h)) + 1);
}
public static void Main()
{
string str= "geeks" ;
Console.WriteLine(findMinInsertions(str.ToCharArray(),
0, str.Length - 1));
}
}
|
Javascript
<script>
function findMinInsertions(str,l,h)
{
if (l > h)
return Number.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) :
(Math.min(findMinInsertions(str, l, h - 1),
findMinInsertions(str, l + 1, h)) + 1)
}
let str= "geeks" ;
document.write(findMinInsertions(str,0, str.length-1));
</script>
|
Time Complexity: O(2n)
Auxiliary Space: O(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:
C++
#include <bits/stdc++.h>
using namespace std;
int findMinInsertionsDP( char str[], int n)
{
int table[n][n], l, h, gap;
memset (table, 0, sizeof (table));
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] :
(min(table[l][h - 1],
table[l + 1][h]) + 1);
return table[0][n - 1];
}
int main()
{
char str[] = "geeks" ;
cout << findMinInsertionsDP(str, strlen (str));
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
int min( int a, int b)
{ return a < b ? a : b; }
int findMinInsertionsDP( char str[], int n)
{
int table[n][n], l, h, gap;
memset (table, 0, sizeof (table));
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] :
(min(table[l][h-1],
table[l+1][h]) + 1);
return table[0][n-1];
}
int main()
{
char str[] = "geeks" ;
printf ( "%d" , findMinInsertionsDP(str, strlen (str)));
return 0;
}
|
Java
import java.io.*;
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()));
}
}
|
Python3
def Min (a, b):
return min (a, b)
def findMinInsertionsDP(str1, n):
table = [[ 0 for i in range (n)]
for i in range (n)]
l, h, gap = 0 , 0 , 0
for gap in range ( 1 , n):
l = 0
for h in range (gap, n):
if str1[l] = = str1[h]:
table[l][h] = table[l + 1 ][h - 1 ]
else :
table[l][h] = ( Min (table[l][h - 1 ],
table[l + 1 ][h]) + 1 )
l + = 1
return table[ 0 ][n - 1 ];
str1 = "geeks"
print (findMinInsertionsDP(str1, len (str1)))
|
C#
using System;
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] :
(Math.Min(table[l, h-1],
table[l+1, h]) + 1);
return table[0, n-1];
}
public static void Main()
{
String str = "geeks" ;
Console.Write(
findMinInsertionsDP(str.ToCharArray(), str.Length));
}
}
|
Javascript
<script>
function findMinInsertionsDP(str,n)
{
let table= new Array(n);
for (let i=0;i<n;i++)
{
table[i]= new Array(n);
}
for (let i=0;i<n;i++)
{
for (let j=0;j<n;j++)
{
table[i][j]=0;
}
}
let l=0, h=0, gap=0;
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] : (Math.min(table[l][h-1],table[l+1][h]) + 1);
}
}
return table[0][n - 1];
}
let str = "geeks" ;
document.write(findMinInsertionsDP(str, str.length));
</script>
|
Time complexity: O(N2)
Auxiliary Space: O(N2)
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:
C++
#include <bits/stdc++.h>
using namespace std;
int lcs( string X, string Y, int m, int n )
{
int L[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[i - 1] == Y[j - 1])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
}
}
return L[m][n];
}
void reverseStr(string& str)
{
int n = str.length();
for ( int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
int findMinInsertionsLCS(string str, int n)
{
string rev = "" ;
rev = str;
reverseStr(rev);
return (n - lcs(str, rev, n, n));
}
int main()
{
string str = "geeks" ;
cout << findMinInsertionsLCS(str, str.length());
return 0;
}
|
C
#include<stdio.h>
#include <string.h>
int max( int a, int b)
{ return (a > b)? a : b; }
int lcs( char *X, char *Y, int m, int n )
{
int L[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[i-1] == Y[j-1])
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = max(L[i-1][j], L[i][j-1]);
}
}
return L[m][n];
}
int findMinInsertionsLCS( char str[], int n)
{
char rev[n+1];
strcpy (rev, str);
strrev(rev);
return (n - lcs(str, rev, n, n));
}
int main()
{
char str[] = "geeks" ;
printf ( "%d" , findMinInsertionsLCS(str, strlen (str)));
return 0;
}
|
Java
import java.util.*;
import java.io.*;
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()));
}
}
|
Python3
def lcs(X, Y, m, n) :
L = [[ 0 for i in range (n + 1 )] for j in range (m + 1 )]
for i in range (m + 1 ) :
for j in range (n + 1 ) :
if (i = = 0 or j = = 0 ) :
L[i][j] = 0
elif (X[i - 1 ] = = Y[j - 1 ]) :
L[i][j] = L[i - 1 ][j - 1 ] + 1
else :
L[i][j] = max (L[i - 1 ][j], L[i][j - 1 ])
return L[m][n]
def findMinInsertionsLCS( Str , n) :
charArray = list ( Str )
charArray.reverse()
revString = "".join(charArray)
return (n - lcs( Str , revString , n, n))
Str = "geeks"
print (findMinInsertionsLCS( Str , len ( Str )))
|
C#
using System;
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[i - 1] == Y[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];
}
static int findMinInsertionsLCS( string str, int n)
{
char [] charArray = str.ToCharArray();
Array.Reverse(charArray);
string revString = new string (charArray);
return (n - lcs(str, revString , n, n));
}
static void Main()
{
string str = "geeks" ;
Console.WriteLine(findMinInsertionsLCS(str,str.Length));
}
}
|
Javascript
<script>
function lcs(X, Y, m, n)
{
let L = new Array(m+1);
for (let i = 0; i < m + 1; i++)
{
L[i] = new Array(n+1);
for (let j = 0; j < n + 1; j++)
{
L[i][j] = 0;
}
}
let 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[i - 1] == Y[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];
}
function findMinInsertionsLCS(str, n)
{
let revString = str.split( '' ).reverse().join( '' );
return (n - lcs(str, revString , n, n));
}
let str = "geeks" ;
document.write(findMinInsertionsLCS(str, str.length));
</script>
|
Time complexity: O(N2)
Auxiliary Space: O(N2)
Space Optimization Method: The above code can be space optimized by using only 1d array instead of 2d array. In the dp table we only need previous row and current row elements.
C++
#include <bits/stdc++.h>
using namespace std;
int lcs(string X, string Y, int m, int n)
{
vector< int > prev(n + 1, 0), curr(n + 1, 0);
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0)
prev[j] = 0;
else if (X[i - 1] == Y[j - 1])
curr[j] = prev[j - 1] + 1;
else
curr[j] = max(prev[j], curr[j - 1]);
}
prev = curr;
}
return prev[n];
}
void reverseStr(string& str)
{
int n = str.length();
for ( int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
int findMinInsertionsLCS(string str, int n)
{
string rev = "" ;
rev = str;
reverseStr(rev);
return (n - lcs(str, rev, n, n));
}
int main()
{
string str = "geeks" ;
cout << findMinInsertionsLCS(str, str.length());
return 0;
}
|
Java
import java.io.*;
public class GFG {
static int Lcs(String X, String Y, int m, int n)
{
int [] prev = new int [n + 1 ];
int [] curr = new int [n + 1 ];
int i, j;
for (i = 0 ; i <= m; i++) {
for (j = 0 ; j <= n; j++) {
if (i == 0 || j == 0 )
prev[j] = 0 ;
else if (X.charAt(i - 1 ) == Y.charAt(j - 1 ))
curr[j] = prev[j - 1 ] + 1 ;
else
curr[j]
= Math.max(prev[j], curr[j - 1 ]);
}
prev = curr;
}
return prev[n];
}
static int FindMinInsertionsLCS(String str, int n)
{
StringBuilder tmp = new StringBuilder();
tmp.append(str);
tmp.reverse();
String rev = tmp.toString();
return (n - Lcs(str, rev, n, n));
}
public static void main(String[] args)
{
String str = "geeks" ;
System.out.println(
FindMinInsertionsLCS(str, str.length()));
}
}
|
Python3
def lcs(X, Y, m, n):
prev = [ 0 for i in range (n + 1 )]
curr = [ 0 for i in range (n + 1 )]
for i in range (m + 1 ):
for j in range (n + 1 ):
if i = = 0 or j = = 0 :
prev[j] = 0
elif X[i - 1 ] = = Y[j - 1 ]:
curr[j] = prev[j - 1 ] + 1
else :
curr[j] = max (prev[j], curr[j - 1 ])
prev = curr
return prev[n]
def reverseStr( str ):
return str [:: - 1 ]
def findMinInsertionsLCS( str , n):
rev = reverseStr( str )
return (n - lcs( str , rev, n, n))
if __name__ = = "__main__" :
str = "geeks"
print (findMinInsertionsLCS( str , len ( str )))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int Lcs( string X, string Y, int m, int n)
{
int [] prev = new int [n + 1];
int [] curr = new int [n + 1];
int i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0)
prev[j] = 0;
else if (X[i - 1] == Y[j - 1])
curr[j] = prev[j - 1] + 1;
else
curr[j]
= Math.Max(prev[j], curr[j - 1]);
}
prev = curr;
}
return prev[n];
}
static int FindMinInsertionsLCS( string str, int n)
{
char [] tmp = str.ToCharArray();
Array.Reverse(tmp);
string rev = new string (tmp);
return (n - Lcs(str, rev, n, n));
}
static void Main( string [] args)
{
string str = "geeks" ;
Console.WriteLine(
FindMinInsertionsLCS(str, str.Length));
}
}
|
Javascript
function lcs(X, Y, m, n) {
var prev = new Array(n + 1).fill(0);
var curr = new Array(n + 1).fill(0);
let i, j;
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0) prev[j] = 0;
else if (X[i - 1] == Y[j - 1]) curr[j] = prev[j - 1] + 1;
else curr[j] = Math.max(prev[j], curr[j - 1]);
}
prev = curr;
}
return prev[n];
}
function reverseStr(rever) {
return rever.split( "" ).reverse().join( "" );
}
function findMinInsertionsLCS(str, q) {
var rever = str.slice();
rev = reverseStr(rever);
return q - lcs(str, rev, q, q);
}
var str = "geeks" ;
console.log(findMinInsertionsLCS(str, str.length));
|
Time complexity: O(N2)
Auxiliary Space: O(N)
Related Article :
Minimum number of Appends needed to make a string palindrome
This article is compiled by Aarti_Rathi and Aashish Barnwal.
Last Updated :
11 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...