Check if characters of a given string can be rearranged to form a palindrome in Python

Suppose we have a string s, we have to check whether characters of the given string can be shuffled to make a palindrome or not.

So, if the input is like s = "raaecrc", then the output will be True as we can rearrange this to "racecar" which is a palindrome.

To solve this, we will follow these steps −

  • freq := a map to store all characters and their frequencies in s
  • odd_count := 0
  • for each element i in the list of all values of freq, do
    • if i 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(st) :
   freq = defaultdict(int)
   for char in st :
      freq[char] += 1
   odd_count = 0
   for i in freq.values():
      if i % 2 == 1:
         odd_count = odd_count + 1
      if odd_count > 1:
         return False
   return True
s = "raaecrc"