sagelearnai

Longest Palindrome

Difficulty: Easy · Pattern: Hashing · LeetCode #409

Given letters s (case-sensitive), return the length of the longest palindrome you can build from them, using each letter at most as many times as it appears.

Examples

text
"abccccdd"  →  7    (e.g. "dccaccd")
"a"         →  1
"Aa"        →  1

Hints

  1. Pairs of the same letter can always be placed symmetrically.
  2. At most one letter can occupy the center.

Approach

For each letter count c, use c // 2 * 2 letters (all the pairs). If any count is odd, add 1 for the center. O(n).

Complexity

Time: O(n). Space: O(alphabet).

Python solution
from collections import Counter

def longestPalindrome(s):
    length, odd = 0, False
    for c in Counter(s).values():
        length += c // 2 * 2
        odd = odd or c % 2 == 1
    return length + (1 if odd else 0)
JavaScript solution
function longestPalindrome(s) {
  const c = new Map();
  for (const ch of s) c.set(ch, (c.get(ch) || 0) + 1);
  let len = 0, odd = false;
  for (const v of c.values()) { len += Math.floor(v / 2) * 2; if (v % 2) odd = true; }
  return len + (odd ? 1 : 0);
}