Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Checking for permutation of a palindrome in JavaScript
We are required to write a JavaScript function that takes in a string as the first and the only argument.
The task of our function is to check whether any rearrangement in the characters of the string results into a palindrome string or not. If yes, then our function should return true, false otherwise.
For a string to form a palindrome through rearrangement, at most one character can have an odd frequency. This is because palindromes read the same forwards and backwards.
For example −
If the input string is −
const str = 'amadm';
Then the output should be −
const output = true;
because the string can be rearranged to form 'madam' which is a palindrome string.
How It Works
The algorithm uses a hash map to track character frequencies. When a character appears an even number of times, it can be split evenly on both sides of the palindrome. Only one character can appear an odd number of times (the middle character).
Example
The code for this will be −
const str = 'amadm';
const canFormPalindrome = (str = '') => {
const hash = {};
let count = 0;
for (let i = 0; i < str.length; i++) {
let c = str[i];
if(c === ' '){
continue;
};
if(hash[c]){
delete hash[c];
}else{
hash[c] = true;
};
count++;
};
if(count % 2 === 0){
return Object.keys(hash).length === 0;
}else{
return Object.keys(hash).length === 1;
};
};
console.log(canFormPalindrome(str));
Output
And the output in the console will be −
true
Alternative Approach Using Character Count
Here's a simpler approach that counts character frequencies directly:
const canFormPalindrome2 = (str) => {
const charCount = {};
// Count frequency of each character
for (let char of str) {
if (char !== ' ') {
charCount[char] = (charCount[char] || 0) + 1;
}
}
// Count how many characters have odd frequencies
let oddCount = 0;
for (let count of Object.values(charCount)) {
if (count % 2 === 1) {
oddCount++;
}
}
// At most one character can have odd frequency
return oddCount <= 1;
};
console.log(canFormPalindrome2('amadm')); // true
console.log(canFormPalindrome2('hello')); // false
console.log(canFormPalindrome2('aab')); // true
true false true
Key Points
? For even-length strings: all characters must appear an even number of times
? For odd-length strings: exactly one character can appear an odd number of times
? The algorithm works by toggling character presence in a hash map
? Time complexity: O(n), Space complexity: O(k) where k is unique characters
Conclusion
To check if a string can form a palindrome, count character frequencies. At most one character can have an odd count, which becomes the middle character in the palindrome.
