Rearrange characters to form palindrome if possible

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"



1. Count occurrences of all characters.
2. 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.
3. Initialize two empty strings firstHalf and secondHalf.
4. Traverse the map. For every character with count as count, attach count/2 characters to end of firstHalf and beginning of secondHalf.
5. Finally return the result by appending firstHalf and secondHalf

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP 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 halh 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;
}

chevron_right


Output:

amdma


My Personal Notes arrow_drop_up

Always code as if the guy who ends up maintaining your code will be violent psychopath who knows where you live visit wwwsahilkhoslacoin

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.