Open In App

Check if any anagram of a string is palindrome or not

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 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
/* 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(256).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.charCodeAt(i)]++;

    // Count odd occurring characters
    let odd = 0;
    for (let i = 0; i < 256; 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*/
canFormPalindrome("geeksforgeeks") ? console.log("Yes") : console.log("No");
canFormPalindrome("geeksogeeks") ? console.log("Yes") : console.log("No");

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:

To check if a string can form a palindrome, we count the occurrences of each character. If more than one character appears an odd number of times, the string can’t form a palindrome. We can use a frequency array or a hashmap for counting.

Below is the implementation of the above approach:

C++
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;

bool isPossible(string S) {
    unordered_map<char, int> mp;
    for(auto i : S) {
        mp[i]++;
    }

    int countOdd = 0;
    for(auto i : mp) {
        if(i.second % 2 != 0) {
            countOdd++;
        }
    }

    // If count of characters with odd frequency is more than 1,
    // it means a palindrome cannot be formed. Otherwise, a palindrome can be formed.
    if(countOdd > 1) {
        return false;
    } else {
        return true;
    }
}

int main() {
    string str1 = "geeksogeeks";
    bool result1 = isPossible(str1);
    cout << boolalpha << result1 << endl;

    string str2 = "geeksforgeeks";
    bool result2 = isPossible(str2);
    cout << boolalpha << result2 << endl;

    return 0;
}
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";
    }
}
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[c]++;
            }
            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
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(n) because every character of the string in added in the map which inturn is the length of string.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads