> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Longest Palindrome Python Solution with Tests

> Tested Python solution for LeetCode 409 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 409, Easy. Topics: Hash Table, String, Greedy. [View on LeetCode](https://leetcode.com/problems/longest-palindrome/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 409   # by problem number
lcpy gen -s longest_palindrome   # by problem name
```

## 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.

### Examples

```
Input: s = "abccccdd"
Output: 7
```

**Explanation:** One longest palindrome that can be built is "dccaccd", whose length is 7.

```
Input: s = "a"
Output: 1
```

**Explanation:** The longest palindrome that can be built is "a", whose length is 1.

### Constraints

* `1 <= s.length <= 2000`
* `s` consists of lowercase and/or uppercase English letters only.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/longest_palindrome/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/longest_palindrome/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def longest_palindrome(self, s: str) -> int:
        char_count: dict[str, int] = {}
        for char in s:
            char_count[char] = char_count.get(char, 0) + 1

        length = 0
        has_odd = False

        for count in char_count.values():
            length += count // 2 * 2
            if count % 2 == 1:
                has_odd = True

        return length + (1 if has_odd else 0)
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(n) | O(1)  |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [NeetCode All](/catalog/neetcode).
