Longest Palindrome
LeetCode 409 | Difficulty: Easyβ
EasyProblem 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?
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?
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.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 80 ms)β
| Metric | Value |
|---|---|
| Runtime | 80 ms |
| Memory | N/A |
| Date | 2018-09-24 |
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β
| Approach | Time | Space |
|---|---|---|
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- 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.