Skip to content
Related Articles
Maximum even length sub-string that is permutation of a palindrome
• Difficulty Level : Easy
• Last Updated : 24 Jan, 2020

Given a string , the task is to find the maximum length of the sub-string of that can be arranged into a Palindrome (i.e at least one of its permutation is a Palindrome). Note that the sub-string must be of even length.

Examples:

Input: str = “124565463”
Output: 6
“456546” is the valid sub-string

Input: str = “122313”
Output: 6

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: Use two variables: start (inclusive) and end (exclusive) to keep track of the starting and ending index of the current sub-string that is being considered in the given string. Also use a dictionary named count which keeps the record of how many times, a character occurs in the current sub-string. Now, there are two possible cases for a sub-string:

1. If the length of the sub-string is odd, then it cannot be considered in the final solution.
2. 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.

Below is the implementation of the above approach:

## C++

 `// C++ code to find the maximum length of ``// sub-string (of even length) which can be``// arranged into a Palindrome``#include ``using` `namespace` `std;`` ` `unordered_map<``int``, ``int``> countt;`` ` `// function that returns true if the given``// sub-string can be arranged into a Palindrome``bool` `canBePalindrome(unordered_map<``int``, ``int``> &countt) ``{``    ``for` `(``auto` `key : countt)``    ``{``        ``if` `(key.second & 1) ``return` `false``;``    ``}``    ``return` `true``;``}`` ` `// This function returns the maximum length of``// the sub-string (of even length) which can be``// arranged into a Palindrome``int` `maxPal(string str,``           ``unordered_map<``int``, ``int``> &countt,``           ``int` `start, ``int` `end)``{``     ` `    ``// If we reach end of the string``    ``if` `(end == str.length()) ``    ``{`` ` `        ``// if string is of even length``        ``if` `((end - start) % 2 == 0)`` ` `            ``// if string can be arranged into a``            ``// palindrome``            ``if` `(canBePalindrome(countt)) ``return` `end - start;`` ` `        ``return` `0;``    ``} ``    ``else` `    ``{`` ` `        ``// Even length sub-string``        ``if` `((end - start) % 2 == 0) ``        ``{`` ` `            ``// Check if current sub-string can be``            ``// arranged into a palindrome``            ``if` `(canBePalindrome(countt))``            ``{``                ``countt[str[end]]++;``                ``return` `max(end - start, maxPal(str, countt, ``                                               ``start, end + 1));``            ``} ``            ``else``            ``{``                ``countt[str[end]]++;``                ``return` `maxPal(str, countt, start, end + 1);``            ``}``        ``}`` ` `        ``// Odd length sub-string``        ``else``        ``{``            ``countt[str[end]]++;``            ``unordered_map<``int``, ``int``> c(countt.begin(), ``                                      ``countt.end());``            ``int` `length = maxPal(str, c, start, end + 1);`` ` `            ``countt[str[end]]--;``            ``countt[str[start]]--;``            ``return` `max(length, maxPal(str, countt, ``                                      ``start + 1, end));``        ``}``    ``}``}`` ` `// Driver code``int` `main(``int` `argc, ``char` `const` `*argv[])``{``    ``string str = ``"124565463"``;``    ``int` `start = 0, end = 0;`` ` `    ``cout << maxPal(str, countt, start, end) << endl;``    ``return` `0;``}`` ` `// This code is contributed by``// sanjeev2552`

## Java

 `// Java code to find the maximum length of ``// sub-string (of even length) which can be ``// arranged into a Palindrome ``import` `java.io.*;``import` `java.util.*;`` ` `class` `GFG ``{`` ` `    ``static` `HashMap count = ``new` `HashMap<>();`` ` `    ``// function that returns true if the given``    ``// sub-string can be arranged into a Palindrome``    ``static` `boolean` `canBePalindrome(HashMap count)``    ``{``        ``for` `(HashMap.Entry entry : count.entrySet())``            ``if` `((entry.getValue() & ``1``) == ``1``)``                ``return` `false``;``        ``return` `true``;``    ``}`` ` `    ``// This function returns the maximum length of``    ``// the sub-string (of even length) which can be``    ``// arranged into a Palindrome``    ``static` `int` `maxPal(String str, ``int` `start, ``int` `end, ``                       ``HashMap count)``    ``{`` ` `        ``// If we reach end of the string``        ``if` `(end == str.length())``        ``{`` ` `            ``// if string is of even length``            ``if` `((end - start) % ``2` `== ``0``)`` ` `                ``// if string can be arranged into a``                ``// palindrome``                ``if` `(canBePalindrome(count))``                    ``return` `end - start;`` ` `            ``return` `0``;``        ``} ``        ``else``        ``{`` ` `            ``// Even length sub-string``            ``if` `((end - start) % ``2` `== ``0``) ``            ``{`` ` `                ``// Check if current sub-string can be``                ``// arranged into a palindrome``                ``if` `(canBePalindrome(count))``                ``{``                    ``count.put((``int``) str.charAt(end),``                    ``count.get((``int``) str.charAt(end)) ==``                    ``null` `? ``1` `: count.get((``int``) str.charAt(end)) + ``1``);``                    ``return` `Math.max(end - start, ``                            ``maxPal(str, start, end + ``1``, count));``                ``}``                ``else``                ``{``                    ``count.put((``int``) str.charAt(end),``                    ``count.get((``int``) str.charAt(end)) ==``                    ``null` `? ``1` `: count.get((``int``) str.charAt(end)) + ``1``);``                    ``return` `maxPal(str, start, end + ``1``, count);``                ``}``            ``}`` ` `            ``// Odd length sub-string``            ``else``            ``{``                ``count.put((``int``) str.charAt(end),``                ``count.get((``int``) str.charAt(end)) == ``                ``null` `? ``1` `: count.get((``int``) str.charAt(end)) + ``1``);``                ``HashMap c = ``new` `HashMap<>(count);`` ` `                ``int` `length = maxPal(str, start, end + ``1``, c);`` ` `                ``count.put((``int``) str.charAt(end),``                ``count.get((``int``) str.charAt(end)) ==``                ``null` `? -``1` `: count.get((``int``) str.charAt(end)) - ``1``);``                 ` `                ``count.put((``int``) str.charAt(start),``                ``count.get((``int``) str.charAt(start)) ==``                ``null` `? -``1` `: count.get((``int``) str.charAt(start)) - ``1``);`` ` `                ``return` `Math.max(length, maxPal(str, ``                            ``start + ``1``, end, count));``            ``}``        ``}``    ``}`` ` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``String str = ``"124565463"``;``        ``int` `start = ``0``, end = ``0``;``        ``System.out.println(maxPal(str, start, end, count));``    ``}``}`` ` `// This code is contributed by``// sanjeev2552`

## Python3

 `# Python3 code to find the maximum length of sub-string ``# (of even length) which can be arranged into a Palindrome`` ` `from` `collections ``import` `defaultdict`` ` `# function that returns true if the given ``# sub-string can be arranged into a Palindrome``def` `canBePalindrome(count):    ``    ``for` `key ``in` `count:``        ``if` `count[key] ``%` `2` `!``=` `0``:``            ``return` `False`            `    ``return` `True``     ` `# This function returns the maximum length of ``# the sub-string (of even length) which can be ``# arranged into a Palindrome``def` `maxPal(string, count, start, end):``     ` `    ``# If we reach end of the string``    ``if` `end ``=``=` `len``(string):`` ` `        ``# if string is of even length``        ``if` `(end``-``start) ``%` `2` `=``=` `0``:`` ` `            ``# if string can be arranged into a``            ``# palindrome``            ``if` `canBePalindrome(count) ``=``=` `True``:``                ``return` `end``-``start``                 ` `        ``return` `0``         ` `    ``else``:``         ` `        ``# Even length sub-string``        ``if` `(end``-``start) ``%` `2` `=``=` `0``:``             ` `            ``# Check if current sub-string can be ``            ``# arranged into a palindrome``            ``if` `canBePalindrome(count) ``=``=` `True``:``                ``count[string[end]] ``+``=` `1``                ``return` `max``(end``-``start, maxPal(string, count, start, end ``+` `1``))``                 ` `            ``else``:``                ``count[string[end]] ``+``=` `1``                ``return` `maxPal(string, count, start, end ``+` `1``)``         ` `        ``# Odd length sub-string  ``        ``else``:``             ` `            ``count[string[end]] ``+``=` `1``            ``length ``=` `maxPal(string, count.copy(), start, end ``+` `1``)``             ` `            ``count[string[end]] ``-``=` `1``            ``count[string[start]] ``-``=` `1``            ``return` `max``(length, maxPal(string, count, start ``+` `1``, end))``             ` `# Driver code``string ``=` `'124565463'``start, end ``=` `0``, ``0``count ``=` `defaultdict(``lambda` `: ``0``)`` ` `print``(maxPal(string, count, start, end))`
Output:
```6
```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live

My Personal Notes arrow_drop_up