Hackbright Code Challenges

Anagram of Palindrome: Solution

Anagram of Palindrome: Solution

Problem

Anagram of Palindrome

Whiteboard

Medium

Challenge

Easier

Concepts

Dictionaries, General

Download

anagram-of-palindrome-solution.zip


The algorithm here is that anagrams of palindromes must have an even number of all letters but one (it’s fine if one letter has an odd number of occurrences, as that could be the middle letter, but if more than one letter has an odd number of occurrences, it can’t be an anagram of a palindrome).

anagramofpalindrome.py
def is_anagram_of_palindrome(word):
    """Is the word an anagram of a palindrome?"""

    # START SOLUTION

    seen = {}

    # Count each letter

    for letter in word:
        count = seen.get(letter, 0)
        seen[letter] = count + 1

    # It's a palindrome if the number of odd-counts is either 0 or 1

    seen_an_odd = False

    for count in seen.values():
        if count % 2 != 0:
            if seen_an_odd:
                return False
            seen_an_odd = True

    return True