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
Remove a Character From String in JavaScript
In JavaScript, a string is a group of characters. Strings are commonly used to store and manipulate text data in JavaScript programs, and removing certain characters is often needed for tasks like: Removing unwanted symbols or spaces.Keeping only the necessary characters.Formatting the text.Methods
3 min read
JavaScript - Characterrs to Opposite Case in a String
Here are the various approaches to convert each character of a string to its opposite case (uppercase to lowercase and vice versa). Using for Loop and if-else Condition - Most CommonIn this approach, we iterate through each character of the string. Using an if-else statement, it checks if each chara
3 min read
How To Split a String Into Segments Of n Characters in JavaScript?
When working with JavaScript, you might encounter a situation where you need to break a string into smaller segments of equal lengths. This could be useful when formatting a serial number, creating chunks of data for processing, or splitting a long string into manageable pieces. In this article, we
6 min read
JavaScript - Strip All Non-Numeric Characters From String
Here are the different methods to strip all non-numeric characters from the string. 1. Using replace() Method (Most Common)The replace() method with a regular expression is the most popular and efficient way to strip all non-numeric characters from a string. [GFGTABS] JavaScript const s1 = "abc
2 min read
JavaScript - Add Characters to a String
Here are the various approaches to add characters to a string in JavaScript Using 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. [GFGTABS] JavaScript const s1 =
2 min read
JavaScript - How to Get Character Array from String?
Here are the various methods to get character array from a string in JavaScript. 1. Using String split() MethodThe split() Method is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument. [GFGTABS] JavaScript let
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 - How to Find the First and Last Character of a String?
Here are the various methods to find the first and last character of a string in JavaScript. 1. Using charAt() MethodThe charAt() method retrieves the character at a specified index. [GFGTABS] JavaScript const s = "JavaScript"; const first = s.charAt(0); const last = s.charAt(s.length - 1)
3 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. [GFGTABS] JavaScript let str = "Hello GFG"; let ch = "!"; let res = str + ch; console.log(res); [/GFGTA
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. [GFGTABS] JavaScript let str = "Hello GFG"; let ch = "!"
1 min read