SDE & MLE Prep

409. Longest Palindrome

Problem

Return the length of the longest palindrome that can be built by rearranging (a subset of) the letters of s. Letters are case-sensitive, so "Aa" is not a palindrome.

Example: "abccccdd" → 7 (e.g. "dccaccd")

A palindrome uses characters in pairs (one on each side) plus at most one odd character in the middle. Sum the pairs; add 1 if any character is left over.

Complexity: O(n).

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