Longest Palindrome
Easy
Topics
Given a string s of lowercase and/or uppercase letters, return the length of the longest palindrome that can be built with those letters (letters are case-sensitive).
Example 1
Input: s = "abccccdd" Output: 7
Example 2
Input: s = "a" Output: 1
Example 3
Input: s = "bb" Output: 2
Constraints
- 1 <= s.length <= 2000
- s consists of lowercase and/or uppercase English letters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
We may reorder freely, so position is irrelevant and only character counts matter. Think about what a palindrome needs: every character is mirrored about the centre, so every character must appear an even number of times — with at most one exception, the single character that can sit exactly at the centre.
So for each distinct character, take as many pairs as it can supply: count // 2 * 2. That consumes all of an even count and all but one of an odd count. Then, if any character had an odd count, one leftover may occupy the centre, adding 1.
Note the centre bonus is at most 1 in total, not one per odd character. Three characters with odd counts still yield only a single centre slot.
Approach
- Count each character.
- Sum
(count // 2) * 2across all of them. - Add 1 if any count was odd.
Dry Run
s = "abccccdd"
counts a:1 b:1 c:4 d:2
pairs a: 0 b: 0 c: 4 d: 2 total 6
odd seen? yes (a and b) +1
answer 7 e.g. "dccaccd"
s = "aaaAaa"
counts a:5 A:1
pairs a: 4 A: 0 total 4
odd seen? yes +1
answer 5 (case-sensitive: 'a' and 'A' are different characters)Complexity
- Time — O(n): one counting pass plus a pass over the distinct characters, bounded by the alphabet.
- Space — O(1): the counter holds at most one entry per distinct character, and the alphabet is the 52 English letters, so it is bounded independently of the 2000-character input. That is the fixed-alphabet convention, worth stating rather than writing O(n).
Common Pitfalls
- Adding 1 for every odd count. Only one character can sit at the centre, so the bonus is capped at 1.
- Writing
count // 2 * 2ascountfor even counts and forgetting the-1for odd ones. The floor-divide form handles both. - Treating the comparison as case-insensitive.
'a'and'A'are distinct here, which the"aaaAaa"case shows. - Trying to construct the palindrome. Only its length is asked for.
- Assuming the answer is
nwhen all counts are even. It is — but via the pair sum, not as a special case.
Full Solution — all languages
class Solution:
def longestPalindrome(self, s):
from collections import Counter
length = 0
odd = False
for v in Counter(s).values():
length += (v // 2) * 2
if v % 2:
odd = True
return length + (1 if odd else 0)import java.util.*;
class Solution {
public int longestPalindrome(String s) {
Map<Character,Integer> f = new HashMap<>();
for (char c : s.toCharArray()) f.merge(c, 1, Integer::sum);
int length = 0;
boolean odd = false;
for (int v : f.values()) {
length += (v / 2) * 2;
if (v % 2 == 1) odd = true;
}
return length + (odd ? 1 : 0);
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int longestPalindrome(string s) {
unordered_map<char,int> f;
for (char c : s) f[c]++;
int length = 0;
bool odd = false;
for (auto& kv : f) {
length += (kv.second / 2) * 2;
if (kv.second % 2) odd = true;
}
return length + (odd ? 1 : 0);
}
};/**
* @param {string} s
* @return {number}
*/ var longestPalindrome = function(s) {
const f = {};
for (const c of s) f[c] = (f[c] || 0) + 1;
let length = 0, odd = false;
for (const k in f) {
length += Math.floor(f[k] / 2) * 2;
if (f[k] % 2) odd = true;
}
return length + (odd ? 1 : 0);
};