Problem 409

Abstract / Summary

Find the length of the longest possible palindrome that can be built using the letters from a given string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0409.py

class Solution:
    def longestPalindrome(self, s: str) -> int:
        if len(s) <= 1:
            return len(s)

        freq = defaultdict(int)
        for c in s:
            freq[c] += 1

        length = 0
        for f in freq:
            length += freq[f] // 2
        length *= 2

        for f in freq:
            if freq[f] % 2 == 1:
                length += 1
                break

        return length
20 lines | 440 bytes | submitted August 15, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (1+ million submissions).

Typical patterns to solve this problem:
  • Greedy
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the maximum possible length of a palindrome that can be assembled from the characters of an input string. It follows a frequency-based strategy: characters that appear an even number of times can be fully used, while at most one character with an odd count can occupy the central position of the palindrome. The function returns this optimal length as an integer.

Key Steps

Early Return for Trivial Inputs

if len(s) <= 1:
    return len(s)

When the string is empty or consists of a single character, the palindrome length is trivially the length of the string itself. This guard avoids unnecessary work for these edge cases.

Frequency Counting

freq = defaultdict(int)
for c in s:
    freq[c] += 1

A defaultdict of integers records how many times each character appears. The loop iterates once over the input, guaranteeing that the counting phase runs in linear time relative to the string length.

Accumulating Paired Characters

length = 0
for f in freq:
    length += freq[f] // 2
length *= 2

For each distinct character, integer division by two yields the number of complete pairs that can be placed symmetrically in the palindrome. Summing these pair counts and then doubling the result produces the total contribution of paired characters to the palindrome length.

Adding a Central Odd Character (If Any)

for f in freq:
    if freq[f] % 2 == 1:
        length += 1
        break

If at least one character has an odd frequency, a single instance can be placed at the palindrome’s center. The loop stops after the first such character is found, ensuring that only one odd character contributes to the final length.

Final Result

return length

The computed length, which respects the constraints of palindrome construction, is returned to the caller.

Edge Cases Handled

The algorithm explicitly addresses several boundary conditions:

  • Empty string - The early return yields 0, which is the correct palindrome length.
  • Single-character string - The early return yields 1, reflecting that a single character forms a palindrome of length one.
  • All characters with even frequencies - The paired-character accumulation fully accounts for the entire string, and the subsequent odd-character loop makes no modification, leaving the length unchanged.
  • All characters with odd frequencies - The paired-character step uses the floor of each count, discarding the unpaired remainder. The odd-character loop then adds exactly one to the length, representing the central character.
  • Mixed even and odd frequencies - The algorithm correctly aggregates all possible pairs and adds a single central character if any odd count remains.

Performance Optimizations

The code exhibits several efficiency-focused choices:

  • Single pass for frequency collection - By iterating over the input string once, the algorithm avoids repeated scans or nested loops.
  • Use of defaultdict - This eliminates the need for explicit key existence checks during counting, reducing overhead.
  • Integer division and multiplication - Computing the number of usable pairs with // 2 and then scaling by 2 avoids repeated addition of two for each pair, which would be less efficient.
  • Early termination after finding an odd character - The second loop stops at the first odd frequency, preventing unnecessary checks of remaining characters once the central slot is filled.
  • Minimal auxiliary storage - Apart from the frequency dictionary, only a few integer variables are maintained, keeping the memory footprint low.

Overall, the implementation delivers a concise and performant solution for determining the longest palindrome length achievable from a given string.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of colorful letter blocks and you want to build the longest possible tower that reads the same forward and backward.

First, look at all the letters and count how many of each color you have in your pile. It is helpful to group them together so you know exactly what you are working with.

To make the tower, you want to put pairs of matching letters on each side. If you have four red blocks, you can put two on the left side and two on the right side. You go through every color you found and take all the pairs you can make. You add these up and multiply by two because every piece on the left needs a matching partner on the right.

After you have used all your pairs, you might have some leftover blocks that do not have a partner. If you have even one lonely block left over, you can pick one of them to put right in the middle of your tower. This makes the tower a little bit taller, but you can only do this once because there is only one middle spot. Once you have placed that middle piece, your tower is finished and as long as it can possibly be.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.26 | σ = 0.89

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Rust Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fengvyi C++
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C
linouk23 C++
lkwq007 Python
pruthvikp Python
qiyuangong Java
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fengvyi C++
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
linouk23 C++
lkwq007 Python
pruthvikp Python
qiyuangong Java
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
wisdompeak C++
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
47 links | 33 authors | 11 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

30 solutions   August 15, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality