VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-palindrome-reorder/

⇱ CSES Solutions - Palindrome Reorder - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Palindrome Reorder

Last Updated : 23 Jul, 2025

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:

  • Count the frequency of all characters in the string S.
  • If more than one character has odd frequency, then it is not possible to reorder the string to make it palindrome.
  • Use two pointers, say left and right to keep track of the positions where we have to keep the next pair of same characters.
  • If exactly one character has odd frequency, then place one such character at the middle of the string and now we will be left will all characters having even frequency which we can distribute equally with same distance from the middle of the string.
  • If no character has odd frequency, then also we can distribute equally with same distance from the middle of the string.
  • Finally, return the constructed palindromic string.

Below is the implementation of the algorithm:


Output
AAACBCAAA

Time Complexity: O(N), where N is the length of input string S.
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: