Longest Palindrome - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "abccccdd"
Output: 7
💡 Note: One longest palindrome is "dccaccd". We can use: 2 d's, 4 c's, and 1 a in the center.
Example 2 — Single Character
$ Input: s = "a"
Output: 1
💡 Note: The longest palindrome is "a" itself, which has length 1.
Example 3 — All Pairs
$ Input: s = "aabbcc"
Output: 6
💡 Note: All characters have even counts, so we can use all of them: "abccba" has length 6.

Constraints

  • 1 ≤ s.length ≤ 2000
  • s consists of lowercase and/or uppercase English letters only

Visualization

Tap to expand
Longest Palindrome: Input → Process → OutputInput String"abccccdd"8 characters totalFrequency Counta:1, b:1, c:4, d:2Even: c,d | Odd: a,bUse all even + 1 centerOutput Length7Max palindrome lengthPossible palindrome construction: "dccaccd"Structure: d-c-c-a-c-c-d (2 pairs of d, 2 pairs of c, 1 center a)
Understanding the Visualization
1
Input
String with mixed case letters: "abccccdd"
2
Process
Count frequencies and determine palindrome structure
3
Output
Maximum possible palindrome length: 7
Key Takeaway
🎯 Key Insight: A palindrome uses all even-count characters and at most one odd-count character in the center
Asked in
Google 25 Amazon 20 Facebook 18 Microsoft 15
185.0K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen