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 StructureIn 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 TechniqueThe 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) AlgorithmIn 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 ProgrammingIn 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 TechniqueIn 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
|