Open In App

Add Minimum Characters at Front to Make String Palindrome in JavaScript

Last Updated : 28 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Approach 1: 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}`);


Output

Minimum characters to make "BABABAA" a palindrome: 2

Approach 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}`);


Output

Minimum characters to make "BABAB" a palindrome: 2


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads