![]() |
VOOZH | about |
Given a string s, check if the characters of the given string can be rearranged to form a palindrome.
Input: s = "geeksgeeks"
Output: True
Explanation: The string can be converted into a palindrome: kgeesseegkInput: s = "geeksforgeeks "
Output: False
Explanation: More than one character has odd frequency, so it cannot form a palindrome.
Table of Content
Common Idea used in all approaches: A set of characters can form a palindrome if at most one character occurs an odd number of times and all characters occur an even number of times.
The idea is to count the frequency of each character by comparing it with every other character using nested loops. A string can form a palindrome if at most one character has an odd frequency.
True False
First, traverse the string and store the frequency of each character in a count array. Then, check the count array to see how many characters have odd frequency. If more than one character has an odd count, it is not possible to form a palindrome; otherwise, it is possible.
Dry run for s = "geeksgeeks":
True False
The idea is to track the frequency of characters using a bitmask instead of counting each one separately. If character set is limited (say only lowercase, i.e., 26 characters), a single integer's bits (total 32 bits typically) can be used to track odd frequencies.
True False