Javascript Program To Find Minimum Insertions To Form A Palindrome | DP-28
Last Updated :
14 May, 2023
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:
JavaScript
<script>
// A Naive recursive JavaScript program to
// find minimum number insertions needed
// to make a string palindrome
// Recursive function to find minimum
// number of insertions
function findMinInsertions(str,l,h)
{
// Base Cases
if (l > h)
return Number.MAX_VALUE;
if (l == h)
return 0;
if (l == h - 1)
return (str[l] == str[h])? 0 : 1;
// Check if the first and last characters
// are same. On the basis of the comparison
// result, decide which subproblem(s) to call
return (str[l] == str[h]) ?
findMinInsertions(str, l + 1, h - 1) :
(Math.min(findMinInsertions(str, l, h - 1),
findMinInsertions(str, l + 1, h)) + 1)
}
// Driver program to test above functions
let str= "geeks";
document.write(
findMinInsertions(str, 0,
str.length-1));
// This code is contributed by rag2127
</script>
Output:
3
Memoisation based approach(Dynamic Programming):
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.
This gave rise to use dynamic programming approach to store the results of subproblems which can be used later. In this apporach we will go with memoised version and in the next one with tabulation version.
Algorithm:
- Define a function named findMinInsertions which takes a character array str, a two-dimensional vector dp, an integer l and an integer h as arguments.
- If l is greater than h, then return INT_MAX as this is an invalid case.
- If l is equal to h, then return 0 as no insertions are needed.
- If l is equal to h-1, then check if the characters at index l and h are same. If yes, then return 0 else return 1. Store the result in the dp[l][h] matrix.
- If the value of dp[l][h] is not equal to -1, then return the stored value.
- Check if the first and last characters of the string str are same. If yes, then call the function findMinInsertions recursively by passing arguments str, dp, l+1, and h-1.
- If the first and last characters of the string str are not same, then call the function findMinInsertions recursively by passing arguments str, dp, l, and h-1 and also call the function recursively by passing arguments str, dp, l+1, and h. The minimum of the two calls is the answer. Add 1 to it, as one insertion is required to make the string palindrome. Store this result in the dp[l][h] matrix.
- Return the result stored in the dp[l][h] matrix.
Below is the implementation of the approach:
JavaScript
// JavaScript program to find minimum
// number insertions needed to make a string
// palindrome
function findMinInsertions(str, dp, l, h) {
// Base Cases
if (l > h) {
return Number.MAX_SAFE_INTEGER;
}
if (l === h) {
return 0;
}
if (l === h - 1) {
return (dp[l][h] = (str[l] === str[h]) ? 0 : 1);
}
if (dp[l][h] !== -1) {
return dp[l][h];
}
// Check if the first and last characters
// are same. On the basis of the comparison
// result, decide which subproblem(s) to call
return (
dp[l][h] = str[l] === str[h] ? findMinInsertions(str, dp, l + 1, h - 1)
: Math.min(
findMinInsertions(str, dp, l, h - 1),
findMinInsertions(str, dp, l + 1, h))
+ 1);
}
// Driver code
const str = "geeks";
const n = str.length;
// initialize dp array
const dp = new Array(n).fill(null).map(
() => new Array(n).fill(-1));
// Function call
console.log(findMinInsertions(str, dp, 0, n - 1));
// This code is contributed by Chandramani Kumar
Time complexity: O(N^2) where N is size of input string.
Auxiliary Space: O(N^2) as 2d dp array has been created to store the states. Here N is size of input string.
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:
JavaScript
<script>
// A Javascript solution for Dynamic Programming
// based program to find minimum number
// insertions needed to make a string
// palindrome
// A DP function to find minimum number
// of insertions
function findMinInsertionsDP(str,n)
{
// Create a table of size n*n. table[i][j]
// will store minimum number of insertions
// needed to convert str[i..j] to a palindrome.
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;
// Fill the 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] :
(Math.min(table[l][h - 1], table[l + 1][h]) + 1);
}
}
// Return minimum number of insertions
// for str[0..n-1]
return table[0][n - 1];
}
// Driver code
let str = "geeks";
document.write(
findMinInsertionsDP(str, str.length));
// This code is contributed by avanitrachhadiya2155
</script>
Output:
3
Time complexity: O(N^2)
Auxiliary Space: O(N^2)
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:
JavaScript
<script>
// An LCS based Javascript program to find
// minimum number insertions needed to make
// a string palindrome
/* Returns length of LCS for X[0..m-1],
Y[0..n-1]. See http://goo.gl/bHQVP for
details of this function */
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;
/* Following steps build L[m+1][n+1] in
bottom up fashion. Note that L[i][j]
contains length of LCS of X[0..i-1]
and Y[0..j-1] */
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]);
}
}
/* L[m][n] contains length of LCS for
X[0..n-1] and Y[0..m-1] */
return L[m][n];
}
// LCS based function to find minimum number
// of insertions
function findMinInsertionsLCS(str, n)
{
let revString = str.split('').reverse().join('');
// The output is length of string minus
// length of lcs of str and it reverse
return (n - lcs(
str, revString , n, n));
}
// Driver code
let str = "geeks";
document.write(
findMinInsertionsLCS(str, str.length));
// This code is contributed by unknown2108
</script>
Output:
3
Time complexity: O(N^2)
Auxiliary Space: O(N^2)
Please refer complete article on Minimum insertions to form a palindrome | DP-28 for more details!
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read