Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 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
Advertisements