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:
C++
#include <bits/stdc++.h>
using namespace std;
// function to construct a palindromic string
string solve(string S)
{
int N = S.length();
string ans(N, ' ');
// frequency array to count the occurrence of each
// character
int freq[26] = {};
for (int i = 0; i < N; i++) {
freq[S[i] - 'A'] += 1;
}
// Count the number of character having odd frequency
int cnt = 0;
for (int i = 0; i < 26; i++) {
if (freq[i] % 2 != 0) {
cnt += 1;
}
}
// If more than one characters have odd frequency, then
// no solution exists
if (cnt > 1)
return "NO SOLUTION";
int left = 0, right = N - 1;
for (int i = 0; i < N; i++) {
if (freq[S[i] - 'A'] % 2 == 1) {
ans[N / 2] = S[i];
freq[S[i] - 'A'] -= 1;
}
while (freq[S[i] - 'A'] > 0) {
ans[left++] = ans[right--] = S[i];
freq[S[i] - 'A'] -= 2;
}
}
return ans;
}
int main()
{
// Sample Input
string S = "AAAACACBA";
cout << solve(S) << endl;
return 0;
}
Java
import java.util.Arrays;
public class PalindromicString {
// function to construct a palindromic string
static String solve(String S) {
int N = S.length();
char[] ans = new char[N];
// frequency array to count the occurrence of each character
int[] freq = new int[26];
for (int i = 0; i < N; i++) {
freq[S.charAt(i) - 'A'] += 1;
}
// Count the number of characters having odd frequency
int cnt = 0;
for (int i = 0; i < 26; i++) {
if (freq[i] % 2 != 0) {
cnt += 1;
}
}
// If more than one character has odd frequency, then no solution exists
if (cnt > 1)
return "NO SOLUTION";
int left = 0, right = N - 1;
for (int i = 0; i < 26; i++) {
while (freq[i] > 1) {
ans[left++] = ans[right--] = (char) ('A' + i);
freq[i] -= 2;
}
}
for (int i = 0; i < 26; i++) {
if (freq[i] == 1) {
ans[N / 2] = (char) ('A' + i);
break;
}
}
return new String(ans);
}
public static void main(String[] args) {
// Sample Input
String S = "AAAACACBA";
System.out.println(solve(S));
}
}
// This code is contributed by shivamgupta0987654321
JavaScript
// Function to construct a palindromic string
function solve(S) {
const N = S.length;
const ans = new Array(N);
// Frequency array to count the occurrence of each character
const freq = new Array(26).fill(0);
for (let i = 0; i < N; i++) {
freq[S.charCodeAt(i) - 65] += 1;
}
// Count the number of characters having odd frequency
let cnt = 0;
for (let i = 0; i < 26; i++) {
if (freq[i] % 2 !== 0) {
cnt += 1;
}
}
// If more than one character has odd frequency, then no solution exists
if (cnt > 1)
return "NO SOLUTION";
let left = 0, right = N - 1;
for (let i = 0; i < 26; i++) {
while (freq[i] > 1) {
ans[left++] = ans[right--] = String.fromCharCode(65 + i);
freq[i] -= 2;
}
}
for (let i = 0; i < 26; i++) {
if (freq[i] === 1) {
ans[Math.floor(N / 2)] = String.fromCharCode(65 + i);
break;
}
}
return ans.join('');
}
// Sample Input
const S = "AAAACACBA";
console.log(solve(S));
Python3
# function to construct a palindromic string
def solve(S):
N = len(S)
ans = [' '] * N
# frequency array to count the occurrence of each character
freq = [0] * 26
for i in range(N):
freq[ord(S[i]) - ord('A')] += 1
# Count the number of characters having odd frequency
cnt = 0
for i in range(26):
if freq[i] % 2 != 0:
cnt += 1
# If more than one character has odd frequency, then no solution exists
if cnt > 1:
return "NO SOLUTION"
left, right = 0, N - 1
for i in range(N):
if freq[ord(S[i]) - ord('A')] % 2 == 1:
ans[N // 2] = S[i]
freq[ord(S[i]) - ord('A')] -= 1
while freq[ord(S[i]) - ord('A')] > 0:
ans[left] = ans[right] = S[i]
left += 1
right -= 1
freq[ord(S[i]) - ord('A')] -= 2
return ''.join(ans)
# Sample Input
S = "AAAACACBA"
print(solve(S))
Time Complexity: O(N), where N is the length of input string S.
Auxiliary Space: O(1)
Similar Reads
R Program to Check if a String is a Palindrome In this article, we explore a simple yet essential task in programming: checking whether a given string is a palindrome. A palindrome is a sequence of characters that reads the same forwards and backwards, making it a common problem in text processing and string manipulation. We'll delve into the lo
5 min read
POTD Solutions | 27 Octâ 23 | Minimum Deletions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Dynamic Programming but will also help you build up problem-solving skills. POT
10 min read
Rearrange characters of a string to make it a concatenation of palindromic substrings Given a string S consisting of lowercase alphabets, the task is to check whether the given string can be rearranged such that the string can be split into non-overlapping palindromic substrings of at least length 2. If found to be true, then print "Yes". Otherwise, print "No". Examples: Input: S = "
6 min read
Return a Palindromic String after removing minimum length Prefix from given String Given a string B, the task is to find the minimum length prefix of the string which, when removed and added to the end of the string, will make the string a palindrome. Return the palindromic string. If no such string exists, we need to determine that. Examples: Input: "aabb"Output: "abba"Explanatio
5 min read
Make all Strings palindrome by swapping characters from adjacent Strings Given an array of strings S[] of size X where each string has length N. In one move, you can swap the ith character of two adjacent strings, the task is to find the minimum number of moves to make every string a palindrome. If this is not possible, print -1. Examples: Input: S[] = {"13", "21", "32"}
10 min read
Minimum cuts required to convert a palindromic string to a different palindromic string Given palindromic string s, the task is to find minimum k, such that you can cut this string into k+1 parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string s. If it is impossible then print -1.Examples: Input : string = "civic
15+ min read