Problem Walkthrough

Longest Palindrome LeetCode 409 Guide

Counting character frequencies where even counts contribute fully and odd counts contribute count-1 — plus one center character if any odd count exists.

7 min read|

Longest Palindrome

LeetCode 409

Problem Overview

LeetCode 409 — Longest Palindrome — gives you a string consisting of uppercase and lowercase letters and asks for the length of the longest palindrome that can be built with those characters. You do not have to use all characters, but you cannot add new ones. The answer is an integer — the maximum length, not the string itself.

For example, given "abccccdd", the answer is 7. One valid palindrome is "dccaccd": the four c's form the mirrored pairs in the middle, the two d's form the outer pair, and one of the a's or b's sits at the center. You leave behind one of a or b unused.

The problem is rated Easy but is a foundational string problem that teaches the core palindrome structure insight: every palindrome is symmetric, which means characters must appear in pairs — with at most one character allowed at the center.

  • Input: string s of length 1 to 2000, consisting of uppercase and lowercase ASCII letters
  • Case-sensitive: 'A' and 'a' are treated as different characters
  • Goal: return the length of the longest palindrome buildable from the characters in s
  • You may use the letters in any order
  • Output: a single integer (length only, not the palindrome string itself)

Palindrome Structure

A palindrome reads the same forwards and backwards. This mirrored structure means every character must appear on both sides of the palindrome — except for at most one character that can sit at the exact center. Any character with an even count can contribute all of its occurrences as symmetric pairs. Any character with an odd count can contribute count-1 occurrences as pairs, leaving one leftover.

Even-count characters are maximally efficient: every occurrence contributes to the palindrome. Odd-count characters waste exactly one occurrence — the unpaired remainder. The key insight is that at most one of those remainders can be rescued: you can place exactly one character at the center position, turning an odd-length or even-length structure into a palindrome.

This structural observation converts the problem into pure arithmetic: sum all even counts, add count-1 for each odd count (rounding down to the nearest even), then add 1 if any character had an odd count (to use one remainder as the center).

💡

The Formula

Sum all even counts fully. For each odd count, add count-1 (the largest even number below it). Then add 1 if any odd count existed — that one remainder becomes the center character. This gives the maximum palindrome length in a single pass.

Frequency Counting

The algorithm starts by counting the frequency of every character in the string. In Python this is a one-liner with Counter; in Java you use a HashMap<Character, Integer> or a fixed-size array of 128 (covering all ASCII characters). Since the problem is case-sensitive, 'A' and 'a' are counted separately.

Once you have the frequency map, iterate over the counts. For each count, add count // 2 * 2 to the result — this is the largest even number less than or equal to count, representing all the pairs you can form. Simultaneously, track whether any count is odd using a boolean flag has_odd.

After the loop, if has_odd is true, add 1 to the result to account for the single center character. The final result is the maximum palindrome length.

  1. 1Build a frequency map: count occurrences of each character in s
  2. 2Initialize result = 0, has_odd = false
  3. 3For each frequency count in the map: add count // 2 * 2 to result
  4. 4If count % 2 == 1, set has_odd = true
  5. 5After the loop: if has_odd, add 1 to result
  6. 6Return result

The Center Character

At most one character can occupy the center position of a palindrome. In "aba" the center is 'b'; in "abba" there is no center (it is even-length). The center is what allows a palindrome to have odd total length — and it is always a single character with an odd frequency.

The has_odd flag captures this elegantly. If any character had an odd frequency, at least one remainder exists. You pick exactly one of those remainders as the center and add 1 to the total. It does not matter which character you choose for the center — any odd-count character's leftover works. The formula automatically maximizes the length.

Notice that even if five different characters each had odd counts, you can only use one of those five remainders as the center. The other four remainders are simply discarded. This is why the adjustment is always +1 at most, regardless of how many odd-count characters exist.

ℹ️

Alternative Formula

An equivalent approach: result = total_chars - number_of_odd_count_chars + (1 if any_odd else 0). This counts what we keep (total minus one wasted per odd-count char) then restores one for the center. Both formulas give identical results.

Walk-Through Example

Consider the input "abccccdd". First build the frequency map: a=1, b=1, c=4, d=2. Now apply the formula: for c (count=4), add 4 (even, no waste); for d (count=2), add 2; for a (count=1), add 0 (count-1=0) and set has_odd=true; for b (count=1), add 0 and has_odd remains true.

Running total of pairs: 0 (from a) + 0 (from b) + 4 (from c) + 2 (from d) = 6. Since has_odd is true, add 1 for the center. Final answer: 7. One valid palindrome: "dccaccd" — d pairs wrap the outside, c pairs form the inner body, one 'a' sits at center. The lone 'b' is discarded.

Verification: length of "dccaccd" is 7. The two d's (one pair), the four c's (two pairs), and one center a account for 2 + 4 + 1 = 7 characters. Correct.

  1. 1Input: "abccccdd"
  2. 2Frequencies: a=1, b=1, c=4, d=2
  3. 3Pairs from a: 0 (odd count, sets has_odd=true)
  4. 4Pairs from b: 0 (odd count, has_odd already true)
  5. 5Pairs from c: 4 (even count, contributes fully)
  6. 6Pairs from d: 2 (even count, contributes fully)
  7. 7Sum of pairs: 0 + 0 + 4 + 2 = 6
  8. 8has_odd is true, add 1 for center character
  9. 9Answer: 6 + 1 = 7

Code Walkthrough — Python and Java

Python solution uses Counter for frequency counting, then iterates the values. The core loop: result += count // 2 * 2 for each count; set has_odd if count % 2 == 1. After the loop, return result + (1 if has_odd else 0). Time complexity O(n) for counting and iterating; space complexity O(1) since there are only 52 possible characters (a-z, A-Z). Java uses a HashMap or int[128] for ASCII, same logic.

A Python one-liner alternative: sum(c // 2 * 2 for c in Counter(s).values()) + (1 if any(c % 2 for c in Counter(s).values()) else 0). This computes the pair sum and center addition in two passes but is slightly less efficient due to the double Counter call. The loop version is cleaner and more readable.

Both Python and Java implementations run in O(n) time where n is the string length. The space is O(1) — bounded by the alphabet size (52 for this problem), not the input size. This is optimal since you must read each character at least once.

⚠️

Length Not String

This problem asks for the LENGTH of the longest palindrome — not the palindrome string itself. If asked to construct the actual palindrome string, you would need to build it from the frequency map: collect all even-count characters as pairs, arrange them symmetrically, and place one odd-count character in the center.

Ready to master algorithm patterns?

YeetCode flashcards help you build pattern recognition through active recall and spaced repetition.

Start practicing now