Given a string, convert the string to palindrome without any modifications like adding a character, removing a character, replacing a character etc.
Examples:
Input : "mdaam" Output : "madam" or "amdma" Input : "abb" Output : "bab" Input : "geeksforgeeks" Output : "No Palindrome"
- Count occurrences of all characters.
- Count odd occurrences. If this count is greater than 1 or is equal to 1 and length of the string is even then obviously palindrome cannot be formed from the given string.
- Initialize two empty strings firstHalf and secondHalf.
- Traverse the map. For every character with count as count, attach count/2 characters to end of firstHalf and beginning of secondHalf.
- Finally return the result by appending firstHalf and secondHalf
Implementation:
C++
// C++ program to rearrange a string to // make palindrome. #include <bits/stdc++.h> using namespace std;
string getPalindrome(string str) { // Store counts of characters
unordered_map< char , int > hmap;
for ( int i = 0; i < str.length(); i++)
hmap[str[i]]++;
/* find the number of odd elements.
Takes O(n) */
int oddCount = 0;
char oddChar;
for ( auto x : hmap) {
if (x.second % 2 != 0) {
oddCount++;
oddChar = x.first;
}
}
/* odd_cnt = 1 only if the length of
str is odd */
if (oddCount > 1
|| oddCount == 1 && str.length() % 2 == 0)
return "NO PALINDROME" ;
/* Generate first half of palindrome */
string firstHalf = "" , secondHalf = "" ;
for ( auto x : hmap) {
// Build a string of floor(count/2)
// occurrences of current character
string s(x.second / 2, x.first);
// Attach the built string to end of
// and begin of second half
firstHalf = firstHalf + s;
secondHalf = s + secondHalf;
}
// Insert odd character if there
// is any
return (oddCount == 1)
? (firstHalf + oddChar + secondHalf)
: (firstHalf + secondHalf);
} int main()
{ string s = "mdaam" ;
cout << getPalindrome(s);
return 0;
} |
Java
// Java program to rearrange a string to // make palindrome import java.util.HashMap;
import java.util.Map.Entry;
class GFG{
public static String getPalindrome(String str)
{ // Store counts of characters
HashMap<Character,
Integer> counting = new HashMap<>();
for ( char ch : str.toCharArray())
{
if (counting.containsKey(ch))
{
counting.put(ch, counting.get(ch) + 1 );
}
else
{
counting.put(ch, 1 );
}
}
/* Find the number of odd elements.
Takes O(n) */
int oddCount = 0 ;
char oddChar = 0 ;
for (Entry<Character,
Integer> itr : counting.entrySet())
{
if (itr.getValue() % 2 != 0 )
{
oddCount++;
oddChar = itr.getKey();
}
}
/* odd_cnt = 1 only if the length of
str is odd */
if (oddCount > 1 || oddCount == 1 &&
str.length() % 2 == 0 )
{
return "NO PALINDROME" ;
}
/* Generate first half of palindrome */
String firstHalf = "" , lastHalf = "" ;
for (Entry<Character, Integer> itr : counting.entrySet())
{
// Build a string of floor(count/2)
// occurrences of current character
String ss = "" ;
for ( int i = 0 ; i < itr.getValue() / 2 ; i++)
{
ss += itr.getKey();
}
// Attach the built string to end of
// and begin of second half
firstHalf = firstHalf + ss;
lastHalf = ss + lastHalf;
}
// Insert odd character if there
// is any
return (oddCount == 1 ) ?
(firstHalf + oddChar + lastHalf) :
(firstHalf + lastHalf);
} // Driver code public static void main(String[] args)
{ String str = "mdaam" ;
System.out.println(getPalindrome(str));
} } // This code is contributed by Satyam Singh |
Python3
# Python3 program to rearrange a string to # make palindrome. from collections import defaultdict
def getPalindrome(st):
# Store counts of characters
hmap = defaultdict( int )
for i in range ( len (st)):
hmap[st[i]] + = 1
# Find the number of odd elements.
# Takes O(n)
oddCount = 0
for x in hmap:
if (hmap[x] % 2 ! = 0 ):
oddCount + = 1
oddChar = x
# odd_cnt = 1 only if the length of
# str is odd
if (oddCount > 1 or oddCount = = 1 and
len (st) % 2 = = 0 ):
return "NO PALINDROME"
# Generate first half of palindrome
firstHalf = ""
secondHalf = ""
for x in sorted (hmap.keys()):
# Build a string of floor(count/2)
# occurrences of current character
s = (hmap[x] / / 2 ) * x
# Attach the built string to end of
# and begin of second half
firstHalf = firstHalf + s
secondHalf = s + secondHalf
# Insert odd character if there
# is any
if (oddCount = = 1 ):
return (firstHalf + oddChar + secondHalf)
else :
return (firstHalf + secondHalf)
# Driver code if __name__ = = "__main__" :
s = "mdaam"
print (getPalindrome(s))
# This code is contributed by ukasp |
C#
// C# program to rearrange a string to // make palindrome using System;
using System.Collections.Generic;
class GFG {
static String getPalindrome( string str)
{
// Store counts of characters
Dictionary< char , int > counting
= new Dictionary< char , int >();
foreach ( char ch in str.ToCharArray())
{
if (counting.ContainsKey(ch)) {
counting[ch] = counting[ch] + 1;
}
else {
counting.Add(ch, 1);
}
}
/* Find the number of odd elements.
Takes O(n) */
int oddCount = 0;
char oddChar = '$' ;
foreach (KeyValuePair< char , int > itr in counting)
{
if (itr.Value % 2 != 0) {
oddCount++;
oddChar = itr.Key;
}
}
/* odd_cnt = 1 only if the length of
str is odd */
if (oddCount > 1
|| oddCount == 1 && str.Length % 2 == 0) {
return "NO PALINDROME" ;
}
/* Generate first half of palindrome */
string firstHalf = "" , lastHalf = "" ;
foreach (KeyValuePair< char , int > itr in counting)
{
// Build a string of floor(count/2)
// occurrences of current character
string ss = "" ;
for ( int i = 0; i < itr.Value / 2; i++) {
ss += itr.Key;
}
// Attach the built string to end of
// and begin of second half
firstHalf = firstHalf + ss;
lastHalf = ss + lastHalf;
}
// Insert odd character if there
// is any
return (oddCount == 1)
? (firstHalf + oddChar + lastHalf)
: (firstHalf + lastHalf);
}
// Driver code
public static void Main()
{
string str = "mdaam" ;
Console.WriteLine(getPalindrome(str));
}
} // This code is contributed by Samim Hossain Mondal. |
Javascript
<script> // JavaScript program to rearrange a string to // make palindrome. function getPalindrome(str)
{ // Store counts of characters
let hmap = new Map();
for (let i = 0; i < str.length; i++){
if (hmap.has(str[i])){
hmap.set(str[i],hmap.get(str[i])+1);
}
else {
hmap.set(str[i],1);
}
}
/* find the number of odd elements.
Takes O(n) */
let oddCount = 0;
let oddChar;
for (let [x,y] of hmap) {
if (y % 2 != 0) {
oddCount++;
oddChar = x;
}
}
/* odd_cnt = 1 only if the length of
str is odd */
if (oddCount > 1
|| oddCount == 1 && str.length % 2 == 0)
return "NO PALINDROME" ;
/* Generate first half of palindrome */
let firstHalf = "" , secondHalf = "" ;
for (let [x,y] of hmap) {
// Build a string of floor(count/2)
// occurrences of current character
let s = "" ;
for (let i = 0; i < Math.floor(y/2); i++){
s += x;
}
// Attach the built string to end of
// and begin of second half
firstHalf = firstHalf + s;
secondHalf = s + secondHalf;
}
// Insert odd character if there
// is any
return (oddCount == 1)
? (firstHalf + oddChar + secondHalf)
: (firstHalf + secondHalf);
} // driver program let s = "mdaam" ;
document.write(getPalindrome(s)); // This code is contributed by shinjanpatra. </script> |
Output
amdma