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 - Greedy Single Pass INPUT String s = "abccccdd" a b c c c c d d Character Frequency: Char a b c d Cnt 1 1 4 2 Even count (4) Even count (2) Odd count (1) ALGORITHM STEPS 1 Count Characters Use array[128] for ASCII 2 Process Each Count Single pass through counts 3 Add Even Pairs result += (count/2) * 2 4 Check for Center Add 1 if odd count exists Calculation: a: 1 --> (1/2)*2 = 0 b: 1 --> (1/2)*2 = 0 c: 4 --> (4/2)*2 = 4 d: 2 --> (2/2)*2 = 2 Sum = 6, has odd --> +1 Result = 7 FINAL RESULT Longest Palindrome Structure: d c c a c c d "dccaccd" mirror Paired chars (6) Center char (1) Output: 7 OK - Length = 7 Key Insight: A palindrome can use ALL characters with even counts (they form symmetric pairs on both sides). At most ONE character with odd count can be placed in the center. We greedily take even portions of all counts: (count/2)*2, then add 1 if any odd count exists. Time: O(n), Space: O(1). TutorialsPoint - Longest Palindrome | Greedy Single Pass Approach
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