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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
Use Case Diagram - Unified Modeling Language (UML) A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read