CSES Solutions - Palindrome Reorder
Last Updated :
20 Mar, 2024
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
Palindrome String Coding Problems A string is called a palindrome if the reverse of the string is the same as the original one.Example: âmadamâ, âracecarâ, â12321â.Palindrome StringProperties of a Palindrome String:A palindrome string has some properties which are mentioned below:A palindrome string has a symmetric structure which m
2 min read
POTD Solutions | 24 Octâ 23 | Palindromic Partitioning View all POTD Solutions 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 pro
6 min read
Shortest Palindromic Substring Given a string you need to find the shortest palindromic substring of the string. If there are multiple answers output the lexicographically smallest. Examples: Input: zyzz Output:y Input: abab Output: a Naive Approach: The approach is similar to finding the longest palindromic substring. We keep tr
8 min read
Smallest Palindrome after replacement Given a string which has some lowercase alphabet characters and one special character dot(.). We need to replace all dots with some alphabet character in such a way that resultant string becomes a palindrome, in case of many possible replacements, we need to choose palindrome string which is lexicog
9 min read
Queries on substring palindrome formation Given a string S, and two types of queries. Type 1: 1 L x, Indicates update Lth index of string S by x character. Type 2: 2 L R, Find if characters between position L and R of string, S can form a palindrome string. If palindrome can be formed print "Yes", else print "No". 1 <= L, R <= |S| Exa
15+ min read