🔗 Problem Link
LeetCode 409 – Longest Palindrome
👉 https://leetcode.com/problems/longest-palindrome/
Introduction
This is one of those problems where you don’t actually need to build the palindrome.
You just need to calculate the maximum possible length of a palindrome that can be formed using the given characters.
The key idea here is understanding:
How palindromes are structured.
Once you understand that, the solution becomes straightforward and elegant.
📌 Problem Understanding
You are given a string s containing:
- Lowercase letters
- Uppercase letters
- Case-sensitive (meaning
'A'and'a'are different)
You must return:
The length of the longest palindrome that can be built using those characters.
You can rearrange characters in any order.
Example 1
One possible palindrome:
Length = 7
Example 2
🧠 Key Observation About Palindromes
A palindrome:
- Reads the same forward and backward.
- Has mirror symmetry.
This means:
- Characters must appear in pairs.
- At most one character can appear an odd number of times (middle character).
🧠 Intuition Behind the Approach
Let’s think step by step:
- Count frequency of each character.
- For every character:
- If frequency is even → use all of them.
- If frequency is odd → use (frequency - 1).
- If at least one odd frequency exists → we can place one odd character in the center.
That’s it.
This is a greedy approach.
💻 Your Code
🔍 Step-by-Step Explanation
1️⃣ Edge Case
If there is only one character, the answer is 1.
2️⃣ Frequency Counting
We count how many times each character appears.
3️⃣ Build the Palindrome Length
len→ stores palindrome lengthodd→ tracks whether any odd frequency exists
4️⃣ Process Each Frequency
If frequency is even → use all characters.
If odd:
- Use
a - 1(which is even) - Keep track that we saw an odd number
5️⃣ Add Middle Character If Needed
If at least one odd frequency exists → we can place one character in the center.
Otherwise → return len.
🎯 Why This Works
In a palindrome:
- All characters must appear in pairs (mirrored sides).
- Only one character can be unpaired (center).
So we:
- Use all even counts.
- Use even portion of odd counts.
- Add one center character if possible.
⏱ Complexity Analysis
Time Complexity: O(n)
- One pass to count frequencies
- One pass over map (max 52 characters: A–Z, a–z)
Space Complexity: O(52) ≈ O(1)
At most 52 distinct characters.
🔥 Cleaner Optimization Idea
We don’t even need a boolean variable.
We can simply:
- Add
a / 2 * 2for every frequency - If total length < original string length → add 1
Example optimized version:
🏁 Final Thoughts
This problem teaches:
- Understanding palindrome structure
- Frequency counting
- Greedy logic
- Handling odd and even counts
It’s a simple but powerful pattern question.
If you truly understand this, you can easily solve problems like:
- Palindrome Permutation
- Longest Palindrome by Concatenating Two Letter Words
- Count Palindromic Subsequences




