More palindromes!

Discovering “palindromality”


The task at hand is to determine whether the letters in a given string could be arranged to form a palindrome.

My first observation is that all characters must occur in the string an even number of times, with the exception of one letter if any. When iterating over each character in the string, I do not need to know how many times it has appeared in the string already, simply whether it has appeared an even or odd number of times. To do this, I could shovel each character into a new array. If I encounter the character a second time I will not add it to the array and instead delete the instance of that character from the array as it is no longer unique.

At the end of the iteration, the only characters in the array will be ones that appeared an odd number of times. Therefore, if the array has a length of 1 or 0, the string can be arranged as a palindrome.

At first, I had only used this code if the given string had an odd number of characters. I was checking against
‘uniq_chars.length == 1'. When I realized the code could account for all string lengths with ‘uniq_chars.length <= 1', I scrapped my other code. It is important to be able to throw out code in favor of an improved solution!
Like what you read? Give Arielle Sullivan a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.