Longest Palindrome — LeetCode 409 Python Solution

EasyGreedyHash TableString
Problem
#409
Pattern
Greedy
Reading time
2 min

The problem

Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, "Aa" is not considered a palindrome.

Example

Input
s = "abccccdd"
Output
7
Explanation
One longest palindrome that can be built is "dccaccd", whose length is 7.

Python solution

Python
class Solution:
    def longestPalindrome(self, s: str) -> int:
        cnt = Counter(s)
        ans = sum(v // 2 * 2 for v in cnt.values())
        ans += int(ans < len(s))
        return ans

Complexity

MeasureComplexity
TimeO(n + |\Sigma|)
SpaceO(|\Sigma|) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 409. Longest Palindrome is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

On a study list

This problem is on Grind 75.

Frequently asked questions

How hard is LeetCode 409. Longest Palindrome?
LeetCode 409. Longest Palindrome is rated Easy on LeetCode.
What is the time complexity of LeetCode 409. Longest Palindrome?
The Python solution on this page runs in O(n + |\Sigma|).
What is the space complexity of LeetCode 409. Longest Palindrome?
The Python solution on this page uses O(|\Sigma|) auxiliary space.
What topics does LeetCode 409. Longest Palindrome cover?
LeetCode 409. Longest Palindrome is tagged Greedy, Hash Table and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview