Check if any anagram of a string is palindrome or not in Python

Suppose we have a string s. We have to check whether an anagram of that string is forming a palindrome or not.

So, if the input is like s = "aarcrec", then the output will be True one anagram of this string is "racecar" which is palindrome.

To solve this, we will follow these steps −

  • freq := a map to store all characters and their frequencies
  • odd_count := 0
  • for each f in list of all values of freq, do
    • if f is odd, then
      • odd_count := odd_count + 1
  • if odd_count > 1, then
    • return False
  • return True

Let us see the following implementation to get better understanding −


 Live Demo

from collections import defaultdict
def solve(s):
   freq = defaultdict(int)
   for char in s:
      freq[char] += 1
   odd_count = 0
   for f in freq.values():
      if f % 2 == 1:
         odd_count += 1
   if odd_count > 1:
      return False
   return True
s = "aarcrec"