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.
Below is the implementation of above approach.
This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
We can do it in O(n) time using a list. Following are detailed steps.
1) Create a character list.
2) Traverse the given string.
3) For every character in the string, remove the character if the list already contains else add to the list.
3) If the string length is even the list is expected to be empty.
4) Or if the string length is odd the list size is expected to be 1
5) On the above two conditions (3) or (4) return true else return false.
- Check if a string can be rearranged to form special palindrome
- Check if the characters in a string form a Palindrome in O(1) extra space
- Check if string can be rearranged so that every Odd length Substring is Palindrome
- Find the count of sub-strings whose characters can be rearranged to form the given word
- Check if characters of one string can be swapped to form other
- Minimum length of the sub-string whose characters can be used to form a palindrome of length K
- Rearrange characters to form palindrome if possible
- Minimal moves to form a string by adding characters or appending string itself
- Check if a doubly linked list of characters is palindrome or not
- Find the player who rearranges the characters to get a palindrome string first
- Minimum characters to be added at front to make string palindrome
- Minimum number of characters to be replaced to make a given string Palindrome
- C Program to Check if a Given String is Palindrome
- Check if a given string is a rotation of a palindrome
- Check if any anagram of a string is palindrome or not