Given a string, Check if characters of the given string can be rearranged to form a palindrome.
For example characters of “geeksogeeks” can be rearranged to form a palindrome “geeksoskeeg”, but characters of “geeksforgeeks” cannot be rearranged to form a palindrome.

A set of characters can form a palindrome if at most one character occurs odd number of times and all characters occur even number of times.

A simple solution is to run two loops, the outer loop picks all characters one by one, the inner loop counts number of occurrences of the picked character. We keep track of odd counts. Time complexity of this solution is O(n2).

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.

Following is C++ implementation of above approach.

[pastacode lang=”cpp” manual=”%23include%20%3Ciostream%3E%0Ausing%20namespace%20std%3B%0A%23define%20NO_OF_CHARS%20256%0A%20%0A%2F*%20function%20to%20check%20whether%20characters%20of%20a%20string%20can%20form%20%0A%20%20%20a%20palindrome%20*%2F%0Abool%20canFormPalindrome(char%20*str)%0A%7B%0A%20%20%20%20%2F%2F%20Create%20a%20count%20array%20and%20initialize%20all%20values%20as%200%0A%20%20%20%20int%20count%5BNO_OF_CHARS%5D%20%3D%20%7B0%7D%3B%0A%20%0A%20%20%20%20%2F%2F%20For%20each%20character%20in%20input%20strings%2C%20increment%20count%20in%0A%20%20%20%20%2F%2F%20the%20corresponding%20count%20array%0A%20%20%20%20for%20(int%20i%20%3D%200%3B%20str%5Bi%5D%3B%20%20i%2B%2B)%0A%20%20%20%20%20%20%20%20count%5Bstr%5Bi%5D%5D%2B%2B%3B%0A%20%0A%20%20%20%20%2F%2F%20Count%20odd%20occurring%20characters%0A%20%20%20%20int%20odd%20%3D%200%3B%0A%20%20%20%20for%20(int%20i%20%3D%200%3B%20i%20%3C%20NO_OF_CHARS%3B%20i%2B%2B)%0A%20%20%20%20%20%20%20%20if%20(count%5Bi%5D%20%26%201)%0A%20%20%20%20%20%20%20%20%20%20%20%20odd%2B%2B%3B%0A%20%20%20%20%20%0A%20%20%20%20%2F%2F%20Return%20true%20if%20odd%20count%20is%200%20or%201%2C%20otherwise%20false%0A%20%20%20%20return%20(odd%20%3C%3D%201)%3B%0A%7D%0A%20%0A%2F*%20Driver%20program%20to%20test%20to%20pront%20printDups*%2F%0Aint%20main()%0A%7B%0A%20%20canFormPalindrome(%22geeksforgeeks%22)%3F%20cout%20%3C%3C%20%22Yes%5Cn%22%3A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20cout%20%3C%3C%20%22No%5Cn%22%3B%0A%20%20canFormPalindrome(%22geeksogeeks%22)%3F%20cout%20%3C%3C%20%22Yes%5Cn%22%3A%20%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20cout%20%3C%3C%20%22No%5Cn%22%3B%0A%20%20return%200%3B%0A%7D” message=”C++ Program” highlight=”” provider=”manual”/]

Output:

No
Yes
[ad type=”banner”]