OneBite.Dev - Coding blog in a bite size

Check if a string is palindrome permutation in Javascript

. In a palindrome, characters have to appear in pairs for the string to be mirrored around the center, except possibly for one character. Here is the javascript solution

What is a palindrome permutation

A string is a palindrome permutation if it can be rearranged to form a palindrome. In a palindrome, characters have to appear in pairs for the string to be mirrored around the center, except possibly for one character, which can be unpaired and sit in the middle in case of an odd length string.

Code sample solution

Here is a JavaScript function that checks if a given string is a palindrome permutation:

function isPalindromePermutation(str) {
  const charCount = new Map();
  let oddCount = 0;
  
  for (let char of str) {
    if (char !== ' ') { // ignore spaces
      char = char.toLowerCase();
      const count = (charCount.get(char) || 0) + 1;
      charCount.set(char, count);
      
      if (count % 2 === 0) {
        oddCount--;
      } else {
        oddCount++;
      }
    }
  }

  // A palindrome can have at most one character with an odd count
  return oddCount <= 1;
}

console.log(isPalindromePermutation('Tact Coa'));  // Should print: true
console.log(isPalindromePermutation('Not a Palindrome'));  // Should print: false

Explanation

In this isPalindromePermutation function, we first normalize the string by converting to lowercase and ignoring spaces. We then count the occurrences of each character using a Map, and we also keep track of the number of characters that have an odd count.

Finally, we return true if there is at most one character with an odd count, which is the condition for a string to be a palindrome permutation.

Time Complexity Info

The time complexity of this function is O(n), where n is the length of the string, because we iterate over the string once. Therefore, this function is quite efficient.

← Check if two strings is a...
Verify only 1 edit action... →
javascript