Open In App
Related Articles

Check if any anagram of a string is palindrome or not

Improve Article
Improve
Save Article
Save
Like Article
Like

Given an anagram string S of length N, the task is to check whether it can be made palindrome or not. 

Examples: 

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

Input: S = geeksgeeks
Output: Yes
Explanation: 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.

Check if any anagram of a string is palindrome or not by counting frequency of each characters:

  • Create a count[] of alphabet size which is typically 256, for storing the frequency of each characters.
  • Traverse the given string and increment count of every character in count[]
  • Traverse the count array and if the count array has more than one odd values, return false. Otherwise, return true

Below is the implementation of the above approach:

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(1) because using constant  (~256) space

Check if any anagram of a string is palindrome or not by counting frequency of each characters in HashMap:

Below is the implementation:

C++




#include <iostream>
#include <unordered_map> //header file for unordered_map
using namespace std;
 
bool isPossible(string S)
{
    unordered_map<char, int>
        a; // create an unordered_map to store the character
           // frequency
    for (char c : S) {
        a++; // increment the frequency of the character
                // in the map
    }
    int c = 0;
    // Iterate through the values
    for (auto v : a) {
        // To check odd or not
        if (v.second % 2
            == 1) { // if the character frequency is odd
            c++;
        }
    }
    if (c > 1) { // if there are more than one character
                 // with odd frequency
        return false;
    }
    return true;
}
 
int main()
{
    bool q = isPossible("geeksogeeks");
    cout << boolalpha << q
         << endl; // print the boolean value
    bool z = isPossible("geeksforgeeks");
    cout << boolalpha << z
         << endl; // print the boolean value
    return 0;
}
// This code is contributed by sarojmcy2e


Java




import java.util.HashMap;
import java.util.Map;
 
public class Main {
    // create an unordered_map to store the character
    // frequency
    public static boolean isPossible(String S)
    {
        Map<Character, Integer> a = new HashMap<>();
        // increment the frequency of the character in the
        // map
        for (char c : S.toCharArray()) {
            a.put(c, a.getOrDefault(c, 0) + 1);
        }
        int c = 0;
        // Iterate through the values
        for (int v : a.values()) {
            // To check odd or not
            if (v % 2
                == 1) { // if the character frequency is odd
                c++;
            }
        }
        if (c > 1) { // if there are more than one character
                     // with odd frequency
            return false;
        }
        return true;
    }
 
    public static void main(String[] args)
    {
        boolean q = isPossible("geeksogeeks");
        System.out.println(
            boolalpha(q)); // print the boolean value
        boolean z = isPossible("geeksforgeeks");
        System.out.println(
            boolalpha(z)); // print the boolean value
    }
 
    // function to convert boolean to string
    public static String boolalpha(boolean b)
    {
        return b ? "True" : "False";
    }
}


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)


C#




using System;
using System.Collections.Generic;
 
class GFG {
    static bool IsPossible(string s)
    {
        Dictionary<char, int> a
            = new Dictionary<char, int>();
 
        // create the dictionary of characters which has
        // the count of characters in string
        foreach(char c in s)
        {
            if (a.ContainsKey(c)) {
                a++;
            }
            else {
                a.Add(c, 1);
            }
        }
 
        int count = 0;
        // iterate through the values
        foreach(int v in a.Values)
        {
            // to check odd or not
            if (v % 2 == 1) {
                count++;
            }
        }
 
        if (count > 1) {
            return false;
        }
        return true;
    }
 
    // Driver code
    static void Main(string[] args)
    {
        bool q = IsPossible("geeksogeeks");
        Console.WriteLine(q);
        bool z = IsPossible("geeksforgeeks");
        Console.WriteLine(z);
    }
}


Javascript




// Javascript program for the above approach
function isPossible(S) {
    const a = {};
     
    // create the object of characters which
    // has the count of characters in String
    for (let i = 0; i < S.length; i++) {
        if (S[i] in a) {
            a[S[i]]++;
        } else {
            a[S[i]] = 1;
        }
    }
 
    let c = 0;
    // Iterate through the values
    for (const v of Object.values(a)) {
        // To check odd or not
        if (v % 2 === 1) {
            c++;
        }
    }
 
    if (c > 1) {
        return false;
    }
    return true;
}
 
const q = isPossible('geeksogeeks');
console.log(q);
const z = isPossible('geeksforgeeks');
console.log(z);
 
// This code is contributed by codebraxnzt


Output

true
false

Time Complexity: O(n) where n is size of string
Auxiliary Space: O(n) because every character of the string in added in the map which inturn is the length of string.

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.


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 29 Sep, 2023
Like Article
Save Article
Similar Reads
Related Tutorials