Add Minimum Characters at Front to Make String Palindrome in JavaScript
Last Updated :
19 Jul, 2024
The minimum characters to add at the front to make the string palindrome means the smallest count of characters required to prepend to the beginning of a given string. It ensures that the resultant string reads the same forwards and backward. This process creates a palindrome from the original string with the least added characters at its start.
Here are some common approaches:
Using Recursion
In this approach, we are using recursion to find the minimum characters needed at the string's end to form a palindrome. It checks if the string is a palindrome; if not, it trims one character from the end and continues recursively until it forms a palindrome, counting the removals.
Example:
JavaScript
function isPalindrome(str) {
return str === str.split('').reverse().join('');
}
function minCharsToPalindrome(str) {
if (isPalindrome(str)) {
return 0;
}
return 1 + minCharsToPalindrome(str.slice(0, -1));
}
const inputString = 'BABABAA';
const result = minCharsToPalindrome(inputString);
console.log(`Minimum characters to make
"${inputString}" a palindrome: ${result}`);
OutputMinimum characters to make "BABABAA" a palindrome: 2
Using Nested Loop Structure
In this approach, we iterates by trimming characters from the end of the string until it forms a palindrome. It checks each iteration if the string is a palindrome by comparing characters from both ends. The process counts the removed characters and stops when the string becomes a palindrome, displaying the total removed characters.
Example:
JavaScript
let inputString = 'BABABAA';
let minChars = 0;
for ( ; ; ) {
let isPalindrome = true;
for (let i = 0; i < inputString.length; i++) {
if (inputString[i] !==
inputString[inputString.length - i - 1]) {
isPalindrome = false;
break;
}
}
if (isPalindrome) {
break;
} else {
minChars++;
inputString = inputString.slice(0, -1);
}
}
console.log(`Minimum characters to make
"${inputString}" a palindrome: ${minChars}`);
OutputMinimum characters to make "BABAB" a palindrome: 2
Using Two-Pointer Technique
The two-pointer technique finds the longest palindromic suffix by comparing characters from the start and end of the string. If characters match, both pointers move inward. If not, the end pointer shifts left, restarting the comparison. The count of unmatched characters gives the result.
Example:
JavaScript
function addMinCharsToFrontTwoPointer(s) {
let n = s.length;
let i = 0, j = n - 1, end = n - 1;
while (i < j) {
if (s[i] === s[j]) {
i++;
j--;
} else {
i = 0;
end--;
j = end;
}
}
return n - end - 1;
}
let s = "abca";
let charsToAdd = addMinCharsToFrontTwoPointer(s);
console.log(charsToAdd);
Using KMP (Knuth-Morris-Pratt) Algorithm
In this approach, we utilize the KMP pattern matching algorithm to find the longest prefix of the given string which is also a suffix of its reverse. The length of this longest prefix will help us determine the minimum number of characters needed to make the string a palindrome.
Example:
JavaScript
function computeLPSArray(pattern) {
let lps = new Array(pattern.length).fill(0);
let length = 0;
let i = 1;
while (i < pattern.length) {
if (pattern[i] === pattern[length]) {
length++;
lps[i] = length;
i++;
} else {
if (length !== 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
function minCharsToPalindromeKMP(str) {
let revStr = str.split('').reverse().join('');
let concat = str + '#' + revStr;
let lps = computeLPSArray(concat);
return str.length - lps[lps.length - 1];
}
const inputString = 'ABCD';
const result = minCharsToPalindromeKMP(inputString);
console.log(`Minimum characters to make "${inputString}" a palindrome: ${result}`);
OutputMinimum characters to make "ABCD" a palindrome: 3
Using Dynamic Programming
In this approach, we use dynamic programming to find the minimum number of characters needed to prepend to the string to make it a palindrome. This method builds a 2D table where dp[i][j] represents the minimum number of insertions needed to make the substring s[i...j] a palindrome. We fill this table and derive the final result from it.
Example:
JavaScript
function minInsertionsToMakePalindrome(s) {
let n = s.length;
let dp = Array.from(Array(n), () => Array(n).fill(0));
for (let gap = 1; gap < n; gap++) {
for (let i = 0, j = gap; j < n; i++, j++) {
if (s[i] === s[j]) {
dp[i][j] = dp[i + 1][j - 1];
} else {
dp[i][j] = Math.min(dp[i][j - 1], dp[i + 1][j]) + 1;
}
}
}
return dp[0][n - 1];
}
const inputString = 'ABC';
const result = minInsertionsToMakePalindrome(inputString);
console.log(`Minimum characters to make "${inputString}" a palindrome: ${result}`);
OutputMinimum characters to make "ABC" a palindrome: 2
Using Manacher's Algorithm Inspired Technique
In this approach, we find the longest palindromic suffix of the given string. The minimum characters required to add to the front is the difference between the string length and the length of this longest palindromic suffix.
Example:
JavaScript
function findLongestPalindromicSuffix(s) {
let T = '#';
for (let i = 0; i < s.length; i++) {
T += s[i] + '#';
}
const n = T.length;
const P = new Array(n).fill(0);
let C = 0, R = 0;
for (let i = 1; i < n - 1; i++) {
const iMirror = 2 * C - i;
if (R > i) {
P[i] = Math.min(R - i, P[iMirror]);
}
while (i + 1 + P[i] < n && i - 1 - P[i] >= 0 && T[i + 1 + P[i]] === T[i - 1 - P[i]]) {
P[i]++;
}
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
}
for (let i = n - 2; i > 0; i--) {
if (i - P[i] === 1) {
return (P[i] + 1) / 2;
}
}
return 0;
}
function minCharsToPalindromeManacher(s) {
const maxSuffixLen = findLongestPalindromicSuffix(s);
return s.length - maxSuffixLen;
}
const inputString = 'racecar';
const result = minCharsToPalindromeManacher(inputString);
console.log(`Minimum characters to make "${inputString}" a palindrome: ${result}`);
const inputString2 = 'ABACD';
const result2 = minCharsToPalindromeManacher(inputString2);
console.log(`Minimum characters to make "${inputString2}" a palindrome: ${result2}`);
OutputMinimum characters to make "racecar" a palindrome: 7
Minimum characters to make "ABACD" a palindrome: 5
Similar Reads
JavaScript - Add Characters to a String Here are the various approaches to add characters to a string in JavaScriptUsing the + Operator - Most PopularThe + operator is the simplest way to add characters to a string. It concatenates one or more strings or characters without modifying the original string.JavaScriptconst s1 = "Hello"; const
2 min read
Javascript Program To Find Minimum Insertions To Form A Palindrome | DP-28 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. babaa: Number of insertions required is 0 i.e. aaabcd: Number of insertions re
9 min read
JavaScript - Add a Character to the End of a String These are the following ways to insert a character at the end of the given string:1. Using ConcatenationWe can use the + operator or template literals to append the character.JavaScriptlet str = "Hello GFG"; let ch = "!"; let res = str + ch; console.log(res); OutputHello GFG! 2. Using Template Liter
2 min read
JavaScript - Insert Character at a Given Position in a String These are the following approaches to insert a character at a given position: 1. Using String Concatenation with SlicingSplit the string into two partsâbefore and after the positionâand concatenate the character in between.JavaScriptlet str = "Hello GFG"; let ch = "!"; let idx = 5; let res = str.sli
1 min read
How to check whether a passed string is palindrome or not in JavaScript? We are given a string, our task is to find string is palindrome or not. A palindrome is a series of numbers, strings, or letters that, when read from right to left and left to right, match each other exactly or produce the same series of characters. in simple words when number strings or characters
4 min read
How to check the given string is palindrome using JavaScript ? A palindrome is a word, sentence, or even number that reads the same from the back and from the front. Therefore if we take the input, reverse the string and check if the reversed string and the original string are equal, it means the string is a palindrome, otherwise, it is not. Approach: When the
3 min read
Create a string with multiple spaces in JavaScript We have a string with extra spaces and if we want to display it in the browser then extra spaces will not be displayed. Adding the number of spaces to the string can be done in the following ways. In this article, we are going to learn how to Create a string with multiple spaces in JavaScript. Below
3 min read
Javascript Program to Minimize characters to be changed to make the left and right rotation of a string same Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = âabcdâOutput: 2Explanation:String after the left shift: âbcdaâString after the right shift: âdabc
3 min read
JavaScript - Add a Character to the Beginning of a String These are the following ways to insert a character at the beginning of the given string:1. Using String ConcatenationDirectly prepend the character using the + operator or template literals.JavaScriptlet str = "Hello, World!"; let ch = "*"; let res = ch + str; console.log(res); Output*Hello, World!
2 min read
JavaScript - Insert Character in JS String In JavaScript, characters can be inserted at the beginning, end, or any specific position in a string. JavaScript provides several methods to perform these operations efficiently.At the BeginningTo insert a character at the beginning of a string, you can use string concatenation or template literals
1 min read