• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to secondary sidebar

GoHired

Interview Questions asked in Google, Microsoft, Amazon

Join WeekEnd Online Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

  • Home
  • Best Java Books
  • Algorithm
  • Internship
  • Certificates
  • About Us
  • Contact Us
  • Privacy Policy
  • Array
  • Stack
  • Queue
  • LinkedList
  • DP
  • Strings
  • Tree
  • Mathametical
  • Puzzles
  • Graph

Minimum insertions to form a palindrome

April 15, 2017 by Dhaval Dave

Given a string, find the minimum number of characters to be inserted to form Palindrome string out of given string

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
abcde: Number of insertions required is 4. edcbabcde

Lets first think How to create recursive solution

Case 1 : String abcda : first and last characters are matching so they can create palindrom, so we need to think for rest of the string only ie. bcd.
Case 2 : String abce : first and last characters are not matching so we can think either we can insert character into “abc” to form Palindrom, or We can insert inbetween “bce” to form abce as palindrom.

So recursive formula created is

                    abcea
	       /        |      \
	      /         |        \
          bcea          abce      bce  <- case 3 is only working as str[l] == str[h]
       /   |   \      /   |   \
      /    |    \    /    |    \
    cea  bce    ce  abc   bce      bc  <- case 3 is discrded as str[l] != str[h]

So we can think of recursive solution as follows

return (str[l] == str[h])? findMinInsertions(str, l + 1, h - 1) :
                               (min(findMinInsertions(str, l, h - 1),  findMinInsertions(str, l + 1, h)) + 1);

Base Case For Recursive Solution :

  1. if  l > h (we crossed pointers) return INT_MAX
  2. if l == h  return 0;
    (only one character, which is already palindrome, 0 insertion is required to make it palindrome)
  3. if l == h-1 and if str[l] == str[h]  return 0;
    (if two length string example “aa or ab” and both characters are same ie : “aa” , its already palindrome,
    so return 0)
    if l == h-1 and if str[l] != str[h] return 1;
    (if two length string is there example “ab” and both characters are different , we need 1 insertion to make this string a palindrome one ie “bab” or “aba“

How to derive Recursive solution and from there How to create Dynamic programming solution , we can learn from Video Below

Code :

#include <limits.h>
#include <iostream>
#include <string>
#include <string.h>

using namespace std;

int min(int a, int b){  return a < b ? a : b; }

int findMinInsertionsRec(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])? findMinInsertionsRec(str, l + 1, h - 1):
                               (min(findMinInsertionsRec(str, l, h - 1),
                                   findMinInsertionsRec(str, l + 1, h)) + 1);
}
//Find Minimum Insertion to Form Palindrome Dynamic Programming solution top down Approach
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];
}
////Find Minimum Insertion to Form Palindrome Dynamic Programming solution bottom up Approach
int findMinInsertionsDP2(string& str)
{
	int n = str.size();
	if( n == 0 )
		return 0;
	int table[n][n];
	int i,j;
	for( i = n-1; i >= 0; i-- )
	{
		for( j = i+1; j < n; j++ )
		{
			if( str[i] == str[j] ) 
			{
				if( j-i > 1 )
					table[i][j] = table[i+1][j-1];
			}
			else
			{
				table[i][j] = 1;
				if( j-i > 1 ) 
					table[i][j] = min(table[i][j-1], table[i+1][j])+1;
			}
		}
	}
	return table[0][n-1];
}

int main()
{
    char str[] = "abcd";
    string str1="abcd";
    printf("%d\n", findMinInsertionsRec(str, 0, strlen(str)-1));
    cout << findMinInsertionsDP(str,strlen(str))<<endl;
    cout << findMinInsertionsDP2(str1)<<endl;
    
    return 0;
}

Solution 2 :

You can see in above examples

  • AB   –   1 insertion required   Inverse of String : BA
  • ABA  –  0 insertion required   Inverse of String : ABA
  • ABC  –  2 insertion required    Inverse of String : CBA
  • ABCAD  – 3 insertion required    Inverse of String : DACBA

You can see

  • LCS of AB and BA is 1 : so strlen( AB ) – LCS( AB, BA ) = 1 is number of insertion required
  • LCS of ABA and ABA is 3 : so strlen(ABA) – LCS(ABA,ABA) = 0  is number of insertion required
  • LCS of ABC and CBA is 1 : so strlen(ABC) – LCS(ABC,CBA) = 2 is number of insertion required
  • LCS of ABCAD and DACBA is 2 : so strlen(ABCAD) – LCS(ABCAD,DACBA) = 3 is number of insertion required

Most of Good Companies ask to have good Java programming experience or Good command over Java Language.
To Prepare with Best way for Interview in Java, follow this page

Similar Articles

Filed Under: Amazon Interview Question, Flipkart Interview Questions, Hacker Earth Questions, Interview Questions, Microsoft Interview Questions, problem Tagged With: Dynamic Programming

Reader Interactions

Primary Sidebar

Join WeekEnd Online/Offline Batch from 4-April-2020 on How to Crack Coding Interview in Just 10 Weeks : Fees just 20,000 INR

Join WeekEnd Online/Offline Batch from 4-April-2020

WhatsApp us

Secondary Sidebar

Custom Search

  • How I cracked AMAZON
  • LeetCode
  • Adobe
  • Amazon
  • Facebook
  • Microsoft
  • Hacker Earth
  • CSE Interview

Top Rated Questions

Find the element that appears once others appears thrice

Circular Linked List

write a c program that given a set a of n numbers and another number x determines whether or not there exist two elements in s whose sum is exactly x

Urban Ladder Written Test.

Find position of the only set bit

Walmart Labs Interview Experience

Serialise Deserialise N-ary Tree

Given a string, find the first character which is non-repetitive

N teams are participating. each team plays twice with all other teams. Some of them will go to the semi final. Find Minimum and Maximum number of matches that a team has to win to qualify for finals ?

SAP Off Campus Hiring_ March 2015 Verbal Skills

Implement a generic binary search algorithm for Integer Double String etc

Search element in a matrix with all rows and columns in sorted order

C++ OOPs Part1

Maximum occurred Smallest integer in n ranges

Edit Distance ( Dynamic Programming )

Word Break Problem

The Magic HackerEarth Nirvana solutions Hiring Challenge

CodeChef’ RRCOPY

Practo Hiring Experience

Implement LRU Cache

Linked List V/S Binary Search Tree

Get Minimum element in O(1) from input numbers or Stack

Client Server C program

N Petrol bunks or City arranged in circle. You have Fuel and distance between petrol bunks. Is it possible to find starting point so that we can travel all Petrol Bunks

Reliance Jio Software Developer Interview Experience

Python Array String

C Program for TAIL command of UNIX

flattens 2 D linked list to a single sorted link list

Coin Collection Dynamic Programming

Adobe Interview Questions 8 month Exp

Copyright © 2025 · Genesis Framework · WordPress · Log in