VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-longest-palindrome-formed-by-removing-or-shuffling-chars-from-string/

⇱ Find longest palindrome formed by removing or shuffling chars from string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find longest palindrome formed by removing or shuffling chars from string

Last Updated : 4 Jul, 2022

Given a string, find the longest palindrome that can be constructed by removing or shuffling characters from the string. Return only one palindrome if there are multiple palindrome strings of longest length.

Examples: 

Input:  abc
Output: a OR b OR c

Input:  aabbcc
Output: abccba OR baccab OR cbaabc OR
any other palindromic string of length 6.

Input:  abbaccd
Output: abcdcba OR ...

Input:  aba
Output: aba

We can divide any palindromic string into three parts - beg, mid and end. For palindromic string of odd length say 2n + 1, 'beg' consists of first n characters of the string, 'mid' will consist of only 1 character i.e. (n + 1)th character and 'end' will consists of last n characters of the palindromic string. For palindromic string of even length 2n, 'mid' will always be empty. It should be noted that 'end' will be reverse of 'beg' in order for string to be palindrome.

The idea is to use above observation in our solution. As shuffling of characters is allowed, order of characters doesn't matter in the input string. We first get frequency of each character in the input string. Then all characters having even occurrence (say 2n) in the input string will be part of the output string as we can easily place n characters in 'beg' string and the other n characters in the 'end' string (by preserving the palindromic order). For characters having odd occurrence (say 2n + 1), we fill 'mid' with one of all such characters. and remaining 2n characters are divided in halves and added at beginning and end.

Below is the implementation of above idea 


Output
abcdcba

Time complexity of above solution is O(n) where n is length of the string. Since, number of characters in the alphabet is constant, they do not contribute to asymptotic analysis.
Auxiliary space used by the program is M where M is number of ASCII characters.

Comment
Article Tags:
Article Tags: