Given a string, find the length of the longest palindrome possible from its characters.

For example,

Input: str = ABACCD
Output: 5
Explanation: The longest palindrome is ACBCA or ACDCA or CABAC or CADAC, each having length 5
 
Input: str = AA
Output: 2
Explanation: The longest palindrome is AA, having length 2

A palindrome string consists of characters in pairs, except for one that may form the middle character. The i’th character from the start of the palindrome is the same as the i’th character from the end of the palindrome. There may or may not be a middle character, and it can be any character.

 
The idea is to count the even and odd frequency characters in a string and use that information to construct the longest palindrome possible. For any character with an even count, half of the characters will fit in the left half of the palindrome, and the other half will fit in the right. The middle element can be made up of any character with an odd count. Any character with an odd count of three or more can be divided into even frequency pairs and a single character.

 
This logic can be easily implemented using hashing, using a map or a set.

1. Using Map

The idea is to create a frequency map to hold the count of each character in the string. Then, obtain the count of the even-frequency characters by iterating through the map’s values. Increase the count if the string contains an odd-frequency character, as it can form the middle character of the palindrome.

C++


Download  Run Code

Output:

The length of the longest palindrome is 5

Java


Download  Run Code

Output:

The length of the longest palindrome is 5

Python


Download  Run Code

Output:

The length of the longest palindrome is 5

The time complexity of the above solution is O(n) and requires O(n) extra space for map, where n is the length of the string.

2. Using Set

Alternatively, we can maintain a set to store the unpaired characters in the string and a counter to store the number of pairs. The idea is to iterate over the string, and if the current character is already present in the set, remove it and increase the pair count by one; otherwise, include the current character in the set. The longest palindrome will now have two characters from each pair, one for the left side and one for the right. Any remaining characters in the set can be placed in the middle of the palindrome string.

C++


Download  Run Code

Output:

The length of the longest palindrome is 5

Java


Download  Run Code

Output:

The length of the longest palindrome is 5

Python


Download  Run Code

Output:

The length of the longest palindrome is 5

The time complexity of the above solution is O(n) and requires O(n) extra space for set, where n is the length of the string.