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



Check if any Anagram of a String is Palindrome

An anagram is a rearrangement of the characters of a word or a phrase to generate a new word, using all the original characters exactly once. For example, thing and night are anagrams of each other. While palindrome is a word or phrase that reads the same forward and backward, like madam, racecar.

In this article, we are going to check if any anagram of a string is a palindrome or not, i.e., we are not just checking whether the given string itself is a palindrome, but also whether it can be rearranged in such a way to form a palindrome.

Let us see some example scenarios:

Scenario 1

Input: "ivicc"
Output: True
Explanation: "ivicc" can be rearranged to "civic", which is a palindrome.

Scenario 2

Input: "abc"
Output: False
Explanation: All characters occur only once, i.e., not possible to form a palindrome.

Let's dive into the example to understand more about checking if any anagram of a string is a palindrome or not.

Example 1

Consider the following example, where we are going to check whether the input "carrace" is an anagram palindrome or not.

from collections import Counter
def demo(s):
   x = Counter(s)
   y = sum(1 for count in x.values() if count % 2 != 0)
   return y <= 1
print(demo("carrace"))

Following is the output of the above program:

True

Example 2

In the following example, we are going to consider the input as "abc" and observe the output. which gives output false, because all the characters occur once (More than one odd frequency cannot form a palindrome).

from collections import Counter
def demo(s):
   x = Counter(s)
   y = sum(1 for count in x.values() if count % 2 != 0)
   return y <= 1
print(demo("abc"))

If we run the above program, it will generate the following output:

False
Updated on: 2025-07-30T18:50:48+05:30

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements