Create palindrome by changing each character to neighboring character in JavaScript


Problem

We are required to write a JavaScript function that takes in a string. Our function can do the following operations on the string −

  • each character MUST be changed either to the one before or the one after in the alphabet.
  • "a" can only be changed to "b" and "z" to "y".

Our function should return True if at least one of the outcomes of these operations is a palindrome or False otherwise.

Example

Following is the code −

 Live Demo

const str = 'adfa';
const canFormPalindrome = (str = '') => {
   const middle = str.length / 2;
   for(let i = 0; i < middle; i++){
      const first = str[i].charCodeAt()
      const last = str[str.length - (i + 1)].charCodeAt()
      const distance = Math.abs(last - first)
      if(distance > 2 || distance === 1){
         return false;
      };
   };
   return true;
};
console.log(canFormPalindrome(str));

Output

Following is the console output −

true

Updated on: 20-Apr-2021

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements