Practice › Strings
Longest Palindrome from Letters
Easy · Strings · Asked at Amazon, Google, TCS, Infosys
Using the letters of the string (each at most once, in any order), print the length of the longest palindrome you can build. Letters are case-sensitive: A and a are different.
Input
A single line with the string (letters only).
Output
The length of the longest palindrome.
Constraints
- 1 ≤ length ≤ 10^5
Every pair of equal letters can sit on both sides. Add the even part of each letter’s count, and one extra letter in the middle if any count was odd.
Example 1
Input
abccccdd
Output
7
Example 2
Input
a
Output
1
Hints
- A palindrome is pairs of equal letters around an optional middle letter.
- From a letter that occurs c times you can use c rounded down to even.
- If any count is odd, one leftover letter can go in the middle.
Approach
Count every letter (case-sensitive). Add count − (count mod 2) for each letter, and add 1 at the end if at least one count was odd. The order of letters never matters because we are free to arrange them.
Complexity: O(n) time · O(52) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
map<char, int> cnt;
for (char c : s) cnt[c]++;
long long len = 0;
bool odd = false;
for (auto &p : cnt) {
len += p.second - p.second % 2;
if (p.second % 2) odd = true;
}
cout << len + (odd ? 1 : 0) << "\n";
return 0;
}Python solution
from collections import Counter
s = input().strip()
cnt = Counter(s)
length = sum(c - c % 2 for c in cnt.values())
print(length + (1 if any(c % 2 for c in cnt.values()) else 0))Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
int[] cnt = new int[128];
for (char c : s.toCharArray()) cnt[c]++;
long len = 0;
boolean odd = false;
for (int c : cnt) {
len += c - c % 2;
if (c % 2 == 1) odd = true;
}
System.out.println(len + (odd ? 1 : 0));
}
}Solve Longest Palindrome from Letters online · All practice problems