Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Minimum insertions to make a string palindrome

Moderate
0/80
Average time to solve is 30m
profile
Contributed by
131 upvotes
Asked in companies
FacebookApplePaytm (One97 Communications Limited)

Problem statement

A palindrome string is one that reads the same backward as well as forward.


You are given a string 'str'.


Find the minimum number of characters needed to insert in 'str' to make it a palindromic string.


Example :
Input: 'str' = "abca"

Output: 1

Explanation:
If we insert the character ‘b’ after ‘c’, we get the string "abcba", which is a palindromic string. Please note that there are also other ways possible.


Detailed explanation ( Input/output format, Notes, Images )
Input format:
The first line contains a string 'str', containing lowercase English letters i.e from ‘a’ to ‘z’.


Output format:
The output contains a single integer denoting the minimum number of insertions needed to make 'str' palindrome.


Note:
You do not need to print anything; it has already been taken care of. Just implement the given function.
Sample Input 1:
abca


Sample Output 1:
1


Explanation for input 1:
If we insert the character ‘b’ after ‘c’, we get the string "abcba", which is a palindromic string. Please note that there are also other ways possible.


Sample Input 2:
abcdefg


Sample Output 2:
6


Sample Input 3:
aaaaa


Sample Output 3:
0


Expected time complexity :
The expected time complexity is O(|str| ^ 2).


Constraints:
1 <= |str| <= 1000

Where |str| represents the length of the string 'str'.

Time Limit: 1 sec.
Hint

The very first approach can be to try all possible substrings of the string and minimize the ans among the valid ones.

Approaches (3)
Brute Force
  1. The main idea is to use recursion to reduce the big problem into several small subproblems.
  2. We will call a minimumInsertionsHelper function that returns us the minimum insertions required to make the string palindrome.
  3. The idea is to compare the first character of the string str[i … j] with the last character. Now there are two possibilities.
    • If the first character of the string is the same as the last character, then we will do a recursive call for the remaining string str[i + 1 ... j - 1]. And our answer will be the answer of making the str[i + 1 … j - 1] palindrome.
    • If the first character of the string is different from the last character, then we will make 2 recursive calls, one for str[i + 1 ... j] and other for str[i … j - 1]. Let the answer from the calls is A and B, then our final answer will be min(A, B) + 1.
  4. The algorithm for minimumInsertionsHelper function will be as follow:
    • int minimumInsertionsHelper(string 'str', int 'start', int 'end'):
      • If ('start' >= 'end') :
        • Return  0
      • If str[start] == str[end] :
        • Return minimumInsertionsHelper(str, start + 1, end - 1)
      • Else :
        • 'A' = minimumInsertionsHelper (STR, start + 1, end)
        • 'B' = minimumInsertionsHelper (STR, start, end - 1)
      • Return min(A, B) + 1

 

Let’s understand with an example:

Consider the string  'str' = “abcca” .

  • Initially 'i' = 0 , 'j' = 4. Now, str[i] == str[j], the answer for “abcca” will be the answer for string “bcc”.
  • Now 'i' = 1, 'j' = 3. Now str[i] != str[j]. Now we have 2 choices.
    • First, we add one ‘b’ after ‘c’ in “bcc” so it becomes “bccb” and then recursively find answer for str[2 … 3]. In this case, our answer will be 1 + answer for str[2 … 3].
    • Second, we add one ‘c’ before ‘b’ in “bcc” so it becomes “cbcc” and then recursively find answer for str[1 … 2]. In this case, our answer will be 1 + answer for str[1 … 2].
  • As we want to minimize the number of insertions so the answer for str[1 … 3] = 1 + min( answer for STR[1..2] , answer for STR[2..3]).
  • Now the answer for STR[1.2], i.e. “bc” is 1 and answer for str[2 ... 3], i.e. “cc” is 0. So, the answer for str[1..3] becomes 1 + min(1,0) = 1.
  • So, the final answer is 1.
Time Complexity

O(2 ^ n), where 'n' is the length of the string. 

In the worst case, at every step, we are making 2 recursive calls. Hence, the overall complexity is O(2 ^ n).

Space Complexity

O(n), where 'n' is the length of the string. 

In the worst case, extra space is used by the recursion stack which goes to a maximum depth of 'n'.

Video Solution
Unlock at level 3
(75% EXP penalty)
Code Solution
(100% EXP penalty)
Minimum insertions to make a string palindrome
All tags
Sort by
Search icon

Interview problems

JAVA-DP-TABULATION

public class Solution {

    public static int minInsertion(String s1) {

        int n=s1.length();

        StringBuilder sb=new StringBuilder(s1);

        String s2=sb.reverse().toString();

        int[][] dp=new int[n+1][n+1];

        for(int i=0;i<=n;i++)

        {

            for(int j=0;j<=n;j++)

            {

                if(i==0 || j==0)

                {

                    dp[i][j]=0;

                }else if(s1.charAt(i-1)==s2.charAt(j-1))

                {

                    dp[i][j]=1+dp[i-1][j-1];

                }else

                {

                    dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]);

                }

            }

        }

        int ans=n-dp[n][n];

        return ans;

    }

}

28 views
0 replies
0 upvotes

Interview problems

DP || Best || 100 % || CP

int lps(string str, int n) {

    vector<vector<int>> dp(n, vector<int>(n, 0));

 

    for (int i = 0; i < n; i++) {

        dp[i][i] = 1;

    }

 

    for (int len = 2; len <= n; len++) {

        for (int i = 0; i < n - len + 1; i++) {

            int j = i + len - 1;

            if (str[i] == str[j]) {

                dp[i][j] = 2 + (i + 1 <= j - 1 ? dp[i + 1][j - 1] : 0);

            } else {

                dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);

            }

        }

    }

 

    return dp[0][n - 1];

}

int minimumInsertions(string &str)

{

    // Write your code here.

    // Find LPS (Longest Palindrome Subsequence)

    // and then Min Insertions : N - LPS

    int n=str.size();

    return n-lps(str,n);

 

}

 

71 views
0 replies
0 upvotes

Interview problems

Recurr || Base || easiest || 60% || C++

int lps(string str,int i,int j){

    if(i==j)

     return 1;

 

     if(i>j)

     return 0;

 

     if(str[i]==str[j]){

         return 2+lps(str,i+1,j-1);

     }

     return max(lps(str,i+1,j),lps(str,i,j-1));

}

int minimumInsertions(string &str)

{

    // Write your code here.

    // Find LPS (Longest Palindrome Subsequence)

    // and then Min Insertions : N - LPS

    

    return str.size()-lps(str,0,str.size()-1);

 

}

 

40 views
0 replies
0 upvotes

Interview problems

As simple as it could be in C++

int minimumInsertions(string &s)
{
	// Write your code here.
	int n=s.size();
	string t=s;
	reverse(s.begin(),s.end());
	vector<vector<int>> v(n+1,vector<int>(n+1,0));
	for(int i=0;i<n;i++){
		for(int j=0;j<n;j++){
			if(s[i]==t[j]){
				v[i+1][j+1]=v[i][j]+1;
			}
			else{
				v[i+1][j+1]=max(v[i+1][j],v[i][j+1]);
			}
		}
	}
	return n-v[n][n];
}
56 views
0 replies
0 upvotes

Interview problems

C++ || DP || LCS Approach

This questions is a variation of Longest Common Subsequence.

We know that longest palindrome of a string can be found by finding the lcs of string and reverse of string

 

Now after lcs is found, the remaining elements of input string will be the one not part of the palindrome. They are the ones whose duplicates are missing so they need to be added. 

Eg: abca

Longest palindrome: aa

Remaining elements: bc

So elements to be added b & c

 

As we only need to return the numbers, we can find length of lps(lcs of string and reversed string) and subtract it from the length of the string. 

In above example lps = 2 and string len = 4

Ans = 4 - 2 = 2

 


//function to find length of longest common subsequence
int LCS(string &x, string &y, int n, int m){
  vector<vector<int>> t(n+1, vector<int>(m+1));

  for(int i = 0; i<n+1; i++){
    for(int j = 0; j<m+1; j++){
      if(i==0 || j == 0){
        t[i][j] = 0;
      }
    }
  }
  
  for(int i = 1; i<n+1; i++){
    for(int j = 1; j<m+1; j++){
        if(x[i-1]==y[j-1]){
          t[i][j] = 1 + t[i-1][j-1];        
        }
        else{
          t[i][j] = max(t[i-1][j],t[i][j-1]);
        }
    }
  }

  return t[n][m];
}

//using string and reverse of string to find lcs helps find longest palindrome
//now elements remaining from longest palindrome in lcs can be deleted to make input string palindrom
//or their copy can be added to input string to make palindrome
int minimumInsertions(string &str)
{
	// Write your code here.
    string r = str;
	reverse(str.begin(), str.end()); 
	
	int n = str.length();
	int x = LCS(str,r, n, n);

	return str.length() - x;

}

 

Hope it helps!

34 views
0 replies
0 upvotes
profile

Interview problems

Smallest and Simplest Code in C++!!

int minimumInsertions(string &str)

{

    int n = str.size();

    string s = str;

    reverse(s.begin(), s.end());

    vector<int> prev(n+1, 0), curr(n+1, 0);

    for(int i = 1; i <= n; i++){

        for(int j = 1; j <= n; j++){

            if(s[i-1] == str[j-1]) curr[j] = 1 + prev[j-1];

            else curr[j] = max(curr[j-1], prev[j]);

        }

        prev = curr;

    }

    return n - prev[n];

}

 

41 views
0 replies
1 upvote

Interview problems

DP - Tabulation

int minimumInsertions(string &str)
{
	int n = str.length();
  string t = str;
  reverse(t.begin(), t.end());
  vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
  for(int i = 1; i <= n; i++){
    for (int j = 1; j <= n; j++) {
      if (str[i - 1] == t[j - 1])
        dp[i][j] = 1 + dp[i - 1][j - 1];
      else
        dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
    }
  }
  return n - dp[n][n];
}
69 views
0 replies
0 upvotes

Interview problems

C++ || DP || Simple || ✅✅

int minimumInsertions(string &str)
{
    int n= str.size();
    vector<vector<int>> dp(n+1,vector<int>(n+1,0));
	int ans = 0;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            if(str[i-1]==str[n-j]) dp[i][j] = 1+dp[i-1][j-1];
            else dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
        }
    }
    return n-dp[n][n];
}
59 views
0 replies
0 upvotes

Interview problems

DP SOLUTION || SPACE OPTIMIZATION

#include<bits/stdc++.h>

int minimumInsertions(string &str)
{
	string t = str;
	reverse(t.begin(),t.end());
	int n = str.size();

	// vector<vector<int>> dp(n+1,vector<int>(n+1,0));
	vector<int> prev(n+1,0);
	vector<int> curr(n+1,0);                

	for(int i = 1 ; i<=n ; i++){
		for(int j = 1 ; j<=n ; j++){
			if(str[i-1] == t[j-1]) curr[j] = 1 + prev[j-1];
			else curr[j] = max(prev[j],curr[j-1]);
		}

		prev = curr;
	}                                       

	int longestPalindrome = prev[n];
	int ans = n - longestPalindrome;
	
	return ans;
}
48 views
0 replies
0 upvotes

Interview problems

Space optimization (DP)

def minInsertion(str):

    t=str[::-1]

    n=len(str)

    prev=cur=[0]*(n+1)

    for i in range(n+1):

        prev[i]=0

    for i in range(1,n+1):

        for j in range(1,n+1):

            if str[i-1]==t[j-1]:

                cur[j]=1+prev[j-1]

            else:

                cur[j]=max(prev[j],cur[j-1])

        prev=cur[:]

    return n- prev[n]

python

datastructures

33 views
0 replies
0 upvotes
Full screen
Console