Skip to main content

Longest Palindrome

LeetCode 409 | Difficulty: Easy​

Easy

Problem Description​

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 1:

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

Example 2:

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.

Topics: Hash Table, String, Greedy


Approach​

Hash Map​

Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?

When to use

Need fast lookups, counting frequencies, finding complements/pairs.

Greedy​

At each step, make the locally optimal choice. The challenge is proving the greedy choice leads to a global optimum. Look for: can I sort by some criterion? Does choosing the best option now ever hurt future choices?

When to use

Interval scheduling, activity selection, minimum coins (certain denominations), Huffman coding.

String Processing​

Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 80 ms)​

MetricValue
Runtime80 ms
MemoryN/A
Date2018-09-24
Solution
public class Solution {
public int LongestPalindrome(string s) {
HashSet<char> hs = new HashSet<char>();
if (string.IsNullOrEmpty(s)) return 0;
int count = 0;
foreach (char c in s)
{
if (hs.Contains(c))
{
hs.Remove(c);
count++;
}
else hs.Add(c);
}

if (hs.Count != 0) return count * 2 + 1;
else return count * 2;
}
}

Complexity Analysis​

ApproachTimeSpace
Hash Map$O(n)$$O(n)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Hash map gives O(1) lookup β€” think about what to use as key vs value.