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 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.
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