![]() |
VOOZH | about |
Given a string S, your task is to reorder its letters in such a way that it becomes a palindrome (i.e., it reads the same forwards and backwards).
Examples:
Input: S = "AAAACACBA"
Output: AAACBCAAA
Explanation: We can reorder "AAAACACBA" to "AAACBCAAA" to get a palindrome string.Input: S = "AAABBB"
Output: NO SOLUTION
Explanation: We cannot reorder "AAABBB" to get a palindrome string.
Approach: To solve the problem, follow the below idea:
We can construct the palindrome by recording the frequency of every character in the string S. If the character occurs even number of times in the string, then we can construct the palindromic string by placing equal number of characters at same distance from the middle of the string. Otherwise, if the character occurs odd number of times, then we can only have one occurrence in the middle and then distribute the remaining even number of characters equally at same distance from the middle of the string. Also, we can have at most one character that occurs odd number of times as that character will be placed in the middle.
Step-by-step algorithm:
Below is the implementation of the algorithm:
AAACBCAAA
Time Complexity: O(N), where N is the length of input string S.
Auxiliary Space: O(1)