Longest Palindrome

Try to solve the Longest Palindrome problem.

Statement#

Given a string s that only contains alphabets, return the length of the longest palindrome that may be composed using those letters.

Note: Letters are case-sensitive. Hence, combinations such as “Aa” are not considered palindromes.

Constraints:

  • 11 \leq s.length 103\leq 10^3

  • s consists of lowercase and/or uppercase English letters only.

Examples#

canvasAnimation-image

1 of 2

canvasAnimation-image

2 of 2

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Longest Palindrome

1

(Select all that apply.) Which options are valid palindromes that can be made using the letters in the string given below?

string = “abbjhhrrssS”

A)

“rhbsSsbhr”

B)

"bhrsjsjsrhb”

C)

“bhrsSsrhb”

D)

“SsrhbjbhrsS”

Question 1 of 40 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.

Drag and drop the cards to rearrange them in the correct sequence.

Iterate through the frequencies in the hash map, and calculate the number of pairs of each character that will appear in the longest palindrome of even length.

Iterate through the input string to count the occurrences of each character and store these frequencies in a hash map.

If the length of the longest palindrome of even length is less than the length of the input string, increment it by 1 to adjust for the possibility of an odd-length palindrome.

Multiply the total number of pairs by 2 to find the length of the longest palindrome of even length.


Try it yourself#

Implement your solution in the following coding playground.

We have left the solution to this challenge as an exercise for you. The optimal solution to this problem runs in O(n) time and takes O(n) space. You may try to translate the logic of the solved puzzle into a coded solution.

Python
usercode > main.py
s
Longest Palindrome

Hash Maps: Introduction

Solution: Longest Palindrome