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
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
Add Characters to a String in JavaScript
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
Find Word Character in a String with JavaScript RegExp
Here are the different ways to find word characters in a string with JavaScript RegExp 1. Using \w to Find Word CharactersThe \w metacharacter in regular expressions matches any word character, which includes: A to Z (uppercase letters)a to z (lowercase letters)0 to 9 (digits)Underscore (_)You can u
3 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
How to remove all Non-ASCII characters from the string using JavaScript ?
In this article, we are given a string containing some non-ASCII characters and the task is to remove all non-ASCII characters from the given string. Approaches to remove all Non-ASCII Characters from String: Table of Content Using ASCII values in JavaScript regExUsing Unicode in JavaScript regExUsi
3 min read
JavaScript Program to Replace Characters of a String
Given a String the task is to replace characters of String with a given String in JavaScript. Examples: Input: Str = Welcome to GfG strRepl = GfG newStr = GeeksOutput: Welcome to GeeksTable of Content Using map() & split() method to replace characters from StringUsing String replace() Method to
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
How to replace a character at a particular index in JavaScript ?
To replace a character from a string there are popular methods available, the two most popular methods we are going to describe in this article. The first method is by using the substr() method. And in the second method, we will convert the string to an array and replace the character at the index.
4 min read
How to search a string for a pattern in JavaScript ?
Here are two ways to search a string for a pattern in JavaScript. 1. Using string search() MethodThe JavaScript string search() method is used to serch a specified substing from the given string and regular expression. It returns the index of the first occurrence of the pattern or -1 if the pattern
2 min read