×

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

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Flatten Binary Tree to a linked list

Implementation In this section, we will see the implementation of the binary Tree and its conversion into linked lists. let us proceed: - // Writing a C++ program that will convert a...

4 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Red Black Tree vs AVL Tree: Data Structure

Difference Between Red Black Tree vs AVL Tree Red Black Tree: A red-black tree is referred as self-balancing binary search tree. In red-black, each node stores an extra bit that determines...

4 minutes read.

Circular Linked List

Circular Linked List A circular linked list where all nodes are connected to their next node and last node is connected to the starting node or we can say all nodes...

5 minutes read.

Complete Binary tree

In this article, we will discuss the complete binary tree. But before start discussing the complete binary tree, we should first see a brief description of a binary tree. What is...

7 minutes read.

Burning binary tree

Burn the Binary tree starting from the target node You have given a binary tree and a target node value. Now you have to burn the tree from target node. You...

4 minutes read.

Data Structure Infix to Prefix Conversion

Infix to Prefix Conversion In present time, we use the infix expression in our daily life but the computers are not able to understand this format because they need to keep...

4 minutes read.

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

3 minutes read.

Optimal binary search tree using dynamic programming

Implementation // We are creating a presentation where we will present a recursive method of the optimal binary search tree problem.  #include <bits/stdc++.h> using namespace std; //creating a utility function that will help us...

9 minutes read.

Buffer overflow attack with examples

You have undoubtedly faced the term buffer overflow in your programming journey. Many times it occurs when we try to run a piece of code with user input, but it...

4 minutes read.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Operations of B++ tree

Insertion When we discuss the insertion operation in the B++ tree, this operation helps us in pushing a new element in the tree at any given place. In this case, the...

17 minutes read.

About Data Structures

What exactly are data structures? A data structure is a type of storage that is used to organise and store data. It is a method of organising data on a computer...

5 minutes read.

Finding Rank in a Binary Search Tree

Implementation // writing a C++ program to find out the rank and element in the program.  #include <bits/stdc++.h> using namespace std; struct __nod { int record; __nod *Lft, *Rt; int LftSize; }; __nod* new__nod(int record) { __nod *temp = new __nod; temp->record...

6 minutes read.

Queue Data Structure

Queue in DS: The queue is a non-primitive and linear data structure. It works on the principle of FIFO (First In First Out). That is, the element that is added...

4 minutes read.

Binary Tree Implementation Using Arrays

Implementation Converting a binary tree into a list of arrays is one interesting problem. Let us see that in depth. In this section, we will see the implementation of the binary Trees...

4 minutes read.

Common Operations on various Data Structures

Data structures are ways to organise data in computer memory for quick and effective use. The storage of data uses a variety of data-structures. It is also possible to define...

7 minutes read.

What is Skewed Binary Tree

To understand the skewed binary tree, we must first understand the concept of a binary tree. A binary is generally the one in which every single node has two further...

3 minutes read.

Doubly Linked List

Doubly Linked List Doubly linked list is another kind of Linked list. Doubly linked list contains two pointers for navigation. In this, we can traverse the list in both directions, either...

4 minutes read.