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
Difficulty
and has an acceptance rate of about 55% (1+ million submissions).
Typical patterns to solve this problem:
- Greedy
- Hash Table
- String
AI Disclaimer
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.
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
// 2and then scaling by2avoids 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 266: Palindrome Permutation
- problem 2131: Longest Palindrome by Concatenating Two Letter Words
- problem 2384: Largest Palindromic Number
Solved On The Same Day
- problem 112: Path Sum
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 16: 3Sum Closest
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- 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