Create palindrome by changing each character to neighboring character in JavaScript

We need to write a JavaScript function that determines if we can create a palindrome by changing each character to its neighboring character in the alphabet. Each character can only move one position forward or backward (except 'a' can only go to 'b' and 'z' can only go to 'y').

Problem Requirements

The function must handle these constraints:

  • 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"
  • Return true if at least one transformation outcome creates a palindrome

Solution Approach

We compare characters from both ends of the string moving toward the center. For each pair, we calculate the distance between their ASCII values and check if they can be transformed to match.

Example

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));
true

How It Works

The algorithm works by:

  • Comparing characters from opposite ends of the string
  • Calculating ASCII distance between each pair
  • Distance 0: characters are same (can both change to same neighbor)
  • Distance 2: characters are two positions apart (can meet in the middle)
  • Distance 1 or >2: impossible to create matching pair

Additional Examples

// Test different cases
console.log(canFormPalindrome('abc'));   // false - 'a' and 'c' distance is 2, can work
console.log(canFormPalindrome('abcd'));  // false - 'a' and 'd' distance is 3, too far
console.log(canFormPalindrome('aaa'));   // true - all same characters
console.log(canFormPalindrome('abba'));  // true - already palindrome structure
true
false
true
true

Edge Cases

// Handle boundary characters
console.log(canFormPalindrome('az'));    // false - 'a' and 'z' too far apart
console.log(canFormPalindrome('ab'));    // true - distance of 1, but fails the rule
console.log(canFormPalindrome('ac'));    // true - distance of 2, can meet at 'b'
false
false
true

Conclusion

This solution efficiently checks palindrome possibility by comparing character distances from string ends. The key insight is that only characters with distance 0 or 2 can be transformed to create matching pairs in a palindrome.

Updated on: 2026-03-15T23:19:00+05:30

493 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements