Longest Palindrome (LeetCode 409): Solution and Explanation

Easy
Hash Table
String
Greedy

Given a string of upper and lowercase letters, return the length of the longest palindrome that can be built from its letters in any order. Upper and lowercase versions count as different letters.

Intuition

Because the letters can be rearranged freely, the original order does not matter at all. All that matters is how many copies of each letter there are.

A palindrome is a mirror. Whatever letter sits at position k from the left also sits at position k from the right, so letters get used two at a time, one on each side.

A letter that appears c times can therefore give c // 2 pairs, which is c // 2 * 2 letters. An odd count leaves one copy over.

The only spot without a mirror partner is the exact middle of an odd-length palindrome. So if any letter had a leftover, one leftover can go there and the answer grows by exactly 1. More leftovers cannot help, since there is only one middle.

Approach: Count letters and pair them

  1. Count how many times each letter appears.
  2. Set length = 0.
  3. For each count c, add c // 2 * 2, the letters that can be placed as mirrored pairs.
  4. If length is still less than len(s), at least one letter was left over, so add 1 for the middle.
  5. Return length.

Step-by-step example

s = "abccccdd"
  1. Count the letters: a = 1, b = 1, c = 4, d = 2.
  2. a appears once, so it has no partner and adds 0.
  3. b also appears once and adds 0.
  4. c appears 4 times: two pairs, adding 4. length = 4.
  5. d appears twice: one pair, adding 2. length = 6.
  6. 6 is less than the 8 letters in s, so a leftover exists. One of a or b goes in the middle: length = 7, for example "dccaccd".

Code: Python, Java, C++

1class Solution:
2    def longestPalindrome(self, s: str) -> int:
3        counts = Counter(s)
4        length = 0
5        for c in counts.values():
6            length += c // 2 * 2
7        if length < len(s):
8            length += 1
9        return length
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass to count the letters, then one pass over at most 52 counts.

Space

O(1)

The count table has a fixed size (52 letters, or 128 slots for ASCII), no matter how long s is.

Other approaches

Toggle set (time O(n), space O(1))

Walk the string with a set. If a letter is already in the set, remove it and add 2 to the answer; otherwise add it. At the end add 1 if the set is not empty. Same idea, one pass.

Count odd letters (time O(n), space O(1))

Count how many letters have an odd count, call it odd. The answer is len(s) - odd + 1 when odd > 0, and len(s) otherwise, because each odd letter loses exactly one copy except the one that takes the middle.

Common mistakes

  • Adding 1 for every letter with an odd count. Only one letter can sit in the middle, so the bonus is at most 1 in total.
  • Skipping odd counts entirely. A letter seen 5 times still contributes 4 letters as two pairs.
  • Treating upper and lowercase as the same letter. "Aa" gives 1, not 2.
  • Returning 0 for a single letter. Any one letter is a palindrome of length 1.

Frequently asked questions

Why is only one odd letter allowed?

Every position except the center has a mirror position, so letters there come in pairs. The center is a single slot, so at most one unpaired letter fits.

Do I need to actually build the palindrome?

No. The question only asks for its length, and the length follows from the counts. Building it would just place each pair's letters at mirrored positions and a leftover in the middle.

How is this different from Longest Palindromic Substring?

Here the letters can be rearranged, so it is a counting problem. In Longest Palindromic Substring the order is fixed and you search for a contiguous palindrome, which needs expand-around-center or dynamic programming.