Skip to content
Related Articles

Related Articles

Check if any anagram of a string is palindrome or not

View Discussion
Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 05 Sep, 2022
View Discussion
Improve Article
Save Article

We have given an anagram string and we have to check whether it can be made palindrome o not. 
Examples: 

Input : geeksforgeeks 
Output : No
There is no palindrome anagram of 
given string

Input  : geeksgeeks
Output : Yes
There are palindrome anagrams of
given string. For example kgeesseegk

This problem is basically the same as Check if characters of a given string can be rearranged to form a palindrome. We can do it in O(n) time using a count array. Following are detailed steps. 
1) Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0. 
2) Traverse the given string and increment count of every character. 
3) Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true. 

C++




#include <iostream>
using namespace std;
#define NO_OF_CHARS 256
 
/* function to check whether characters of a string
   can form a palindrome */
bool canFormPalindrome(string str)
{
    // Create a count array and initialize all
    // values as 0
    int count[NO_OF_CHARS] = { 0 };
 
    // For each character in input strings,
    // increment count in the corresponding
    // count array
    for (int i = 0; str[i]; i++)
        count[str[i]]++;
 
    // Count odd occurring characters
    int odd = 0;
    for (int i = 0; i < NO_OF_CHARS; i++) {
        if (count[i] & 1)
            odd++;
 
        if (odd > 1)
            return false;
    }
 
    // Return true if odd count is 0 or 1,
    return true;
}
 
/* Driver program to test to print printDups*/
int main()
{
    canFormPalindrome("geeksforgeeks") ? cout << "Yes\n" : cout << "No\n";
    canFormPalindrome("geeksogeeks") ? cout << "Yes\n" : cout << "No\n";
    return 0;
}

Java




// Java program to Check if any anagram
// of a string is palindrome or not
public class GFG {
    static final int NO_OF_CHARS = 256;
 
    /* function to check whether characters of
      a string can form a palindrome */
    static boolean canFormPalindrome(String str)
    {
        // Create a count array and initialize
        // all values as 0
        int[] count = new int[NO_OF_CHARS];
 
        // For each character in input strings,
        // increment count in the corresponding
        // count array
        for (int i = 0; i < str.length(); i++)
            count[str.charAt(i)]++;
 
        // Count odd occurring characters
        int odd = 0;
        for (int i = 0; i < NO_OF_CHARS; i++) {
            if ((count[i] & 1) != 0)
                odd++;
 
            if (odd > 1)
                return false;
        }
 
        // Return true if odd count is 0 or 1,
        return true;
    }
 
    /* Driver program to test to print printDups*/
    public static void main(String args[])
    {
        System.out.println(canFormPalindrome("geeksforgeeks")
                               ? "Yes"
                               : "No");
        System.out.println(canFormPalindrome("geeksogeeks")
                               ? "Yes"
                               : "No");
    }
}
// This code is contributed by Sumit Ghosh

Python




NO_OF_CHARS = 256
   
""" function to check whether characters of a string
   can form a palindrome """
def canFormPalindrome(string):
     
    # Create a count array and initialize all
    # values as 0
    count = [0 for i in range(NO_OF_CHARS)]
   
    # For each character in input strings,
    # increment count in the corresponding
    # count array
    for i in string:
        count[ord(i)] += 1
   
    # Count odd occurring characters
    odd = 0
    for i in range(NO_OF_CHARS):
        if (count[i] & 1):
            odd += 1
  
        if (odd > 1):
            return False
   
    # Return true if odd count is 0 or 1,
    return True
   
# Driver program to test to print printDups
if(canFormPalindrome("geeksforgeeks")):
    print "Yes"
else:
    print "No"
if(canFormPalindrome("geeksogeeks")):
    print "Yes"
else:
    print "NO"
 
# This code is contributed by Sachin Bisht

C#




// C# program to Check if any anagram
// of a string is palindrome or not
using System;
 
public class GFG {
     
    static int NO_OF_CHARS = 256;
 
    /* function to check whether
    characters of a string can form
    a palindrome */
    static bool canFormPalindrome(string str)
    {
         
        // Create a count array and
        // initialize all values as 0
        int[] count = new int[NO_OF_CHARS];
 
        // For each character in input
        // strings, increment count in
        // the corresponding count array
        for (int i = 0; i < str.Length; i++)
            count[str[i]]++;
 
        // Count odd occurring characters
        int odd = 0;
        for (int i = 0; i < NO_OF_CHARS; i++) {
            if ((count[i] & 1) != 0)
                odd++;
 
            if (odd > 1)
                return false;
        }
 
        // Return true if odd count
        // is 0 or 1,
        return true;
    }
 
    // Driver program
    public static void Main()
    {
        Console.WriteLine(
            canFormPalindrome("geeksforgeeks")
                              ? "Yes" : "No");
                               
        Console.WriteLine(
            canFormPalindrome("geeksogeeks")
                              ? "Yes" : "No");
    }
}
 
// This code is contributed by vt_m.

Javascript




<script>
    // Javascript program to Check if any anagram
    // of a string is palindrome or not
     
    let NO_OF_CHARS = 256;
  
    /* function to check whether
    characters of a string can form
    a palindrome */
    function canFormPalindrome(str)
    {
          
        // Create a count array and
        // initialize all values as 0
        let count = new Array(NO_OF_CHARS);
        count.fill(0);
  
        // For each character in input
        // strings, increment count in
        // the corresponding count array
        for (let i = 0; i < str.length; i++)
            count[str[i].charCodeAt()]++;
  
        // Count odd occurring characters
        let odd = 0;
        for (let i = 0; i < NO_OF_CHARS; i++) {
            if ((count[i] & 1) != 0)
                odd++;
  
            if (odd > 1)
                return false;
        }
  
        // Return true if odd count
        // is 0 or 1,
        return true;
    }
     
    document.write(canFormPalindrome("geeksforgeeks")? "Yes" + "</br>" : "No" + "</br>");
                                
      document.write(canFormPalindrome("geeksogeeks")? "Yes" : "No");
 
// This code is contributed by divyeshrabadiya07.
</script>

Output: 

No
Yes

Time Complexity: O(n)

Auxiliary space: O(256). 

This article is contributed by Aarti_Rathi and Rishabh Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
  

Method 2:

Using built in functions and logic/algo  as follows:

  1. Create a count array of alphabet size which is typically 256. Initialize all values of count array as 0.
  2. Traverse the given string and increment count of every character.
  3. Traverse the count array and if the count array has more than one odd values, return false. Otherwise return true.

We can make use collections module for reducing the number of lines of code without counting it manually using dictionary.

Python3




from collections import Counter
def isPossible(S):
        a=Counter(S)
        #create the dictionary of characters which has the count of characters in String
        a=dict(a)
        #print(a)
        c=0
        #Iterate through the values
        for v in a.values():
          # To chech odd or not
            if v%2==1:
                c+=1
        if c>1:
            return False
        return True
# contributed by Raghavendra SN
q=isPossible('geeksogeeks')
print(q)
z=isPossible('geeksforgeeks')
print(z)

Output

True
False

Time Complexity: O(n) where n is size of string

Auxiliary Space: O(1) because using constant  (~256) space for counter


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!