In: Computer Science
Give an english description of an algorithm which can determine whether or not characters can be arranged into a palindrome when given an input string of X characters. Then, determine order of growth of this algorithm as a function of X. (These characters can only be any of the twenty six lower case alphabet letters.)
search
Sign In
Home
Courses
Hire With Us
Algorithmskeyboard_arrow_down
Data Structureskeyboard_arrow_down
Languageskeyboard_arrow_down
Interview Cornerkeyboard_arrow_down
GATEkeyboard_arrow_down
CS Subjectskeyboard_arrow_down
Studentkeyboard_arrow_down
GBlog
Puzzles
What's New ?
▲
Check if characters of a given string can be rearranged to form a palindrome
Last Updated: 03-03-2020
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.
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
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.
Another approach:
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.
Hope this may help you
Thank you ??