Palindrome Rearranging

Description


Given a string, find out if its characters can be rearranged to form a palindrome.

Note: A palindrome is a string that reads the same left-to-right and right-to-left.

Example

For inputString = "aabb", the output should be palindromeRearranging(inputString) = true.

We can rearrange "aabb" to make "abba", which is a palindrome.

Input/Output

  • [execution time limit] 4 seconds (js)

  • [input] string inputString

A string consisting of lowercase English letters.

Guaranteed constraints: 1 ≤ inputString.length ≤ 50.

  • [output] boolean

true if the characters of the inputString can be rearranged to form a palindrome, false otherwise.

[JavaScript (ES6)] Syntax Tips

1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
    console.log("This prints to the console when you Run Tests");
    return "Hello, " + name;
}

Solution


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function palindromeRearranging(inputString) {
    var odd = 0;
    var arr = inputString.split('');
    var el;
    var pos;
    while (arr.length) {
        el = arr.pop();
        pos = arr.indexOf(el);
        if (pos <0) {
            odd++;
        } else {
            arr.splice(pos,1);
        }
    }
    
    return odd <2;
}