File: longest-palindrome/solution.py

Date: 2026-06-06

Time: 17:27

longest-palindrome/solution.py

Purpose

Solves LeetCode 409 — Longest Palindrome. Given a string of mixed-case English letters, it computes the length of the longest palindrome you could build by rearranging the characters. This is a construction problem, not a substring search — you're picking letters from a bag, not finding a contiguous run.

Key Components

longestPalindrome(s: str) -> int — The sole public function. It counts character frequencies, then greedily takes the largest even portion of each frequency. If any character has an odd count, one extra character can sit in the center of the palindrome.

Flow

1. Counter(s) builds a frequency map in O(n).

2. The loop iterates over counts (not characters — the keys are irrelevant).

3. count // 2 * 2 extracts the largest even number ≤ count. For count=5, that's 4. This is equivalent to count - (count % 2) but makes the "pairs of two" intent explicit.

4. has_odd is a boolean flag set once any count is odd — meaning at least one leftover character exists to place in the palindrome center.

5. return length + hasoddhasodd is True/False, which Python treats as 1/0 in arithmetic. At most one center character contributes.

Patterns

Dependencies

Imports: collections.Counter — the only dependency. No custom data structures or project-level imports.

Imported by: The longest-palindrome/test_solution.py file imports this function directly. The massive "Imported By" list in the prompt is an artifact of the repo's test infrastructure — those other test files don't actually import this solution; they share a common test harness pattern.

Invariants

Error Handling

None. The function assumes valid input per LeetCode constraints: a non-empty string of English letters. No edge-case guards for empty strings (would return 0, which is correct anyway since Counter("").values() is empty and has_odd stays False).

Complexity

Topics to Explore

Beliefs