AlgoInsight

DSA problem

Longest Palindrome

EasyStringsPattern: Frequency Counttop600AmazonGoogle

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, so for example "Aa" is not considered a palindrome.

You do not need to construct the palindrome itself, only report how long the best possible one is. A palindrome reads the same forwards and backwards, so characters must be placed in mirrored pairs around an optional single center character. The goal is to use as many of the available letters as possible while still forming a valid palindrome.

Examples

Example 1
Input: s = "abccccdd"
Output: 7
Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7. We use both d-s, four c-s, and one a as the center.
Example 2
Input: s = "a"
Output: 1
Explanation: The longest palindrome that can be built is "a", whose length is 1.
Example 3
Input: s = "Aa"
Output: 1
Explanation: Letters are case sensitive, so "A" and "a" cannot pair; only one of them can be used as a single-character palindrome.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringhash-tablegreedyfrequency-count

Browse all DSA problems