Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Check If 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 −

Example

 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"
print(solve(s))

Input

"raaecrc"

Output

True
Updated on: 2020-12-30T13:41:36+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements