×

Find Number of Minimum Insertion to Make a String Palindrome

You have been given a string. You have to find out the number of minimum insertions to make this string palindrome. The string will contain only lower case alphabets.

Note:

What is a palindrome?

We call a string or a number palindrome, if it looks same from both front and behind. For example, the string “DAD” is a palindrome. So, from both side one can read the string same. Numbers like 121 is also palindrome.

Input:  “abcd”

Output:    3

Explanation: If we want to make the string palindrome then we have to add three characters. The palindrome string may be “abcdcba” (It is possible to build different sequence but the minimum number of insertions will be same i.e. 3).

Concept behind the solution

This problem can be solved by different approaches. We can use recursion for this solution. But this approach will take more time and space. So, we will use dynamic programming to solve this problem. If we use memorization then it can take more space for big input size. So, it is best to use tabulation approach.

Code:

// Program in C++ to find out the number of minimum insertions to make this string palindrome

#include <bits/stdc++.h>
using namespace std;
int my_fun(string s, int low, int high,vector<vector<int>>& dp)
{
	for(int i=1;i<=high;i++){
            for(int l=0,h=i;h<=high;h++,l++){
         if(s[l]==s[h]){
             dp[l][h]=dp[l+1][h-1];
        }
        else
             dp[l][h]=(min(dp[l+1][h],dp[l][h-1])+1);
        }
        }
        return dp[low][high]; 
}
// memorisation function 
/*int my_fun(string s, int low, int high,vector<vector<int>>& dp){
        if(dp[low][high]!=-1)
            return dp[low][high];
        else if(low==high)
            return 0;
        else if(low==high-1){
           if(s[low]==s[high])
                return 0;
            else 
                return 1;
        }
        else if(s[low]==s[high]){
            return dp[low][high]= my_fun (s,low+1,high-1,dp);
        }
        else
            return dp[low][high]=(min(my_fun (s,low,high-1,dp), my_fun (s,low+1,high,dp))+1);
    }*/
int main()
{
	string s = "abcd";
vector<int> x(s.size()+1,0);
        vector<vector<int>> dp(s.size()+1,x);
	cout << my_fun(s,0,s.size()-1,dp);
	return 0;
}

// Program in C to find out the number of minimum insertions to make this string palindrome

#include <stdio.h>
#include <string.h>
int min(int a, int b)
{ return a < b ? a : b; }
int my_fun(char str[], int n)
{
	int dp[n][n], l, h, i;
	memset(dp, 0, sizeof(dp));
	for (i = 1; i < n; ++i)
		for (l = 0, h = i; h < n; ++l, ++h)
			dp[l][h] = (str[l] == str[h])?
						dp[l+1][h-1] :
						(min(dp[l][h-1],
						dp[l+1][h]) + 1);
	return dp[0][n-1];
}
int main()
{
	char str[] = "abcd";
	printf("%d", my_fun(str, strlen(str)));
	return 0;
}

// Program in JAVA to find out the number of minimum insertions to make this string //palindrome

#include <stdio.h>
#include <string.h>
int min(int a, int b)
{ return a < b ? a : b; }
int my_fun(char str[], int n)
{
	int dp[n][n], l, h, i;
	memset(dp, 0, sizeof(dp));
	for (i = 1; i < n; ++i)
		for (l = 0, h = i; h < n; ++l, ++h)
			dp[l][h] = (str[l] == str[h])?
						dp[l+1][h-1] :
						(min(dp[l][h-1],
						dp[l+1][h]) + 1);
	return dp[0][n-1];
}
int main()
{
	char str[] = "abcd";
	printf("%d", my_fun(str, strlen(str)));
	return 0;
}


# Program in Python to find out the number of minimum insertions to make this string #palindrome

def Min(a, b):
	return min(a, b)
def my_fun(str1, n):
	dp = [[0 for i in range(n)]
				for i in range(n)]
	l, h, i = 0, 0, 0
	for i in range(1, n):
		l = 0
		for h in range(i, n):
			if str1[l] == str1[h]:
				dp[l][h] = dp[l + 1][h - 1]
			else:
				dp[l][h] = (Min(dp[l][h - 1],
								dp[l + 1][h]) + 1)
			l += 1
	return dp[0][n - 1];
str1 = "abcd"
print(my_fun(str1, len(str1)))

// Program in C# to find out the number of minimum insertions to make this string palindrome

using System;
class bn
{
	static int my_fun(char []str, int n)
	{
		int [,]dp = new int[n, n];
		int l, h, i;
		for (i = 1; i < n; ++i)
		for (l = 0, h = i; h < n; ++l, ++h)
			dp[l, h] = (str[l] == str[h])?
						dp[l+1, h-1] :
						(Math.Min(dp[l, h-1],
								dp[l+1, h]) + 1);
		return dp[0, n-1];
	}
	public static void Main()
	{
		String str = "abcd";
		Console.Write(
		my_fun(str.ToCharArray(), str.Length));
	}
}


<script>

// Program in JavaScript to find out the number of minimum insertions to make this //string  palindrome

function my_fun(str,n)
	{
		
		let dp=new Array(n);
		for(let i=0;i<n;i++)
		{
			dp[i]=new Array(n);
		}
				
		for(let i=0;i<n;i++)
		{
			for(let j=0;j<n;j++)
			{
				dp[i][j]=0;
			}
		}	
		
		let l=0, h=0, i=0;
		for (i = 1; i < n; i++)
		{
			for (l = 0, h = i; h < n; l++, h++)
			{
								
				dp[l][h] = (str[l] == str[h]) ? dp[l+1][h-1] : (Math.min(dp[l][h-1],dp[l+1][h]) + 1);
				
			}
		}
		return dp[0][n - 1];
	}
	let str = "abcd";
	document.write(my_fun(str, str.length));
	
	
</script>

Output: 

Find Number of Minimum Insertion to Make a String Palindrome

Related Topics

Operations of B Tree in C++ Language

B tree tends to be a self-aligning and balancing tree that helps us organise our data and document safely. We know that every data or information in the B tree...

9 minutes read.

Types of Linked list

Single linked list  A single linked list is a linked list in which all nodes are connected with each other in sequence. Each node of a singly linked list has two...

7 minutes read.

Lowest Common Ancestor in a Binary Tree

The lowest node in the tree that contains both n1 and n2 as descendants is the lowest common ancestor (LCA), and n1 and n2 are the nodes for which we...

11 minutes read.

Difference between complete and full binary tree

As we all know that the  binary tree is a tree it contains one or two children at each other node. It contains two children's nodes in the Binary tree. The...

6 minutes read.

Right side view of binary tree

The right view of the binary tree is generally known to be that side viewed from the right direction of the point of view. To be more precise, the right-side...

8 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

DFS (Depth-first search) Algorithm: Data Structure

What is DFS (Depth-first search)? The depth first search is a graph traversal algorithm. The idea behind this algorithm is backtracking and it is a kind of recursive algorithm. In the...

3 minutes read.

Application of Stack in Data Structures

In this article, we will discuss all the different applications of stack. What is meant by stack? The stack is a non-primitive linear data structure in which the insertion of the new...

11 minutes read.

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Queue Implementation using stacks Data Structure

Queue Implementation using stacks In this problem, we have stack data structure which supports only push() and pop() operations. We are required to implement a queue data structure using the instances...

4 minutes read.

How to Start Learning DSA

All programmer experiences a point along the way where they wish they could approach a problem in a more effective manner. They finally learn about the terminology DSA while trying...

10 minutes read.

Given a Binary Tree Swap Nodes at K Height

Implementation // Writing a C++ program that will help us exchange the nodes.  #include<bits/stdc++.h> using namespace std; // Creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a function that will help...

8 minutes read.

Find all possible words from board

We have been given a dictionary of words and a board of characters from which we can form strings. Now, we have to check if the string is present in...

5 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

Invert binary tree

Invert binary tree is a mirror image of a tree. It is pretty much the same compared to the only difference: its left and right children are swapped with the...

4 minutes read.

Applications of Different Linked Lists in Data Structure

What is a Linked list? A linked list is a data structure that consists of a sequence of elements, where each containing a reference or ("link") to the next element in...

5 minutes read.

FIFO approach

FIFO is first in first out approach. It is done for the list of elements in data structures where first element will be deleted after another element ia added to it Here,...

6 minutes read.

Arrange consonants and vowels nodes in a linked list

Arrange consonants and vowels nodes in a linked list In this problem, we have given a singly linked list. Here we will arrange the consonants and vowels nodes of the list...

2 minutes read.

Binary tree deletion

This article will discuss the deletion operation's implementation in the binary tree. The deletion operation helps us eliminate an element from the tree. Implementation #include <bits/stdc++.h> using namespace std; /* A binary tree node...

4 minutes read.