Maximum even length sub-string that is permutation of a palindrome in C++

C++Server Side ProgrammingProgramming

Problem statement

Given a string the task is to find the maximum length of the sub-string of that can be arranged into a Palindrome.


If input string = “5432112356” then answer is 6 as maximum palindrome substring is “321123” and its length is 6


  • If the length of the sub-string is odd, then it cannot be considered in the final solutions.
  • If the length of the sub-string is even, then it can be a possible solution only if each character in that sub-string occurs even number of times which can be done using the dictionary count. We check if each character occurs even number of times or not. If yes, then we include it as one of the possible solutions. Then we form the next sub-string by including the next character in the string which can be done by simply incrementing end and check recursively if a sub-string with greater length can be formed which satisfies the given conditions and return the maximum of all possible solutions


 Live Demo

#include <bits/stdc++.h>
using namespace std;
unordered_map<int, int> countt;
bool isPalindromePossible(unordered_map<int, int> &countt) {
   for (auto key : countt) {
      if (key.second & 1) {                                                        
         return false;
      return true;
   int getMaxPalindrome(string str, unordered_map<int, int> &countt, int start, int end) {
      if (end == str.length()) {
         if ((end - start) % 2 == 0)
         if (isPalindromePossible(countt))
         return end - start;
         return 0;
      } else {
      if ((end - start) % 2 == 0) {
         if (isPalindromePossible(countt)) {
            return max(end - start, getMaxPalindrome(str, countt, start, end + 1));
         } else {
            return getMaxPalindrome(str, countt, start, end + 1);
      } else {
         unordered_map<int, int>
         c(countt.begin(), countt.end());
         int length = getMaxPalindrome(str, c, start, end + 1);
         return max(length, getMaxPalindrome(str, countt, start + 1, end));
int main(int argc, char const *argv[]) {
   string str = "5432112356";
   int start = 0, end = 0;
   cout << "Maximum palindrome length = " << getMaxPalindrome(str, countt, start, end) << endl;
   return 0;


When you compile and execute above program. It generates following output −

Maximum palindrome length = 6
Published on 10-Jan-2020 11:45:30