Skip to content
Problem 409 · LeetCode 409(opens in a new tab)

Longest Palindrome

EasyGreedy algorithms

You get a string s of English letters. Using any of its letters, each at most as many times as it appears, build the longest palindrome you can, and return its length. You do not have to use every letter, and the order is up to you.

Upper and lower case count as different letters, so "Aa" is not a palindrome.

Example 1

Input:  s = "ppqqqr"
Output: 5
Why:    "pqrqp": two pairs plus one letter in the middle
2 more examples and the constraints

Example 2

Input:  s = "Aa"
Output: 1
Why:    A and a differ, so only one of them fits

Example 3

Input:  s = "z"
Output: 1
Why:    a single letter is a palindrome

Constraints

  • 1 ≤ length of s ≤ 2,000
  • s holds only the letters a to z and A to Z

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count every letterO(n)
  2. Pair letters as you goO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 2,000 lettersVerdict
Count every letterO(n)
Fine; two short passes
Pair letters as you goO(n)
Best; one pass, no counts

n = length of s. Both are linear; the second skips the pass over the counts.

Edge cases to test

  • Case matters. "Aa" has two different letters, so the answer is 1, not 2.
  • Every letter different. "abcdef" has no pairs; one letter in the middle gives 1.
  • No odd counts. "kkkk" uses every letter and has no middle: 4.
  • Many odd counts. "aaabbbccc" gives three pairs and one middle letter: 7, not 9.

Common mistakes

  • Adding 1 for every letter with an odd count instead of once in total.
  • Skipping odd counts entirely, when n − 1 of those letters still form pairs.
  • Lowercasing the string first, which treats A and a as the same letter.

How to talk through it

  1. 1Clarify. Can I reorder the letters? Do I need every letter? Does case matter?
  2. 2Describe a palindrome. Mirrored pairs around at most one middle letter, so only the counts matter.
  3. 3Count. Sum the even part of every count, then add 1 if any count is odd.
  4. 4Tighten. A set of unpaired letters gives the same answer in one pass with no second loop.
  5. 5Test out loud. Run "Aa", "z", "kkkk" and "aaabbbccc" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?