Python 2404.py
class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
freq = defaultdict(int)
for n in nums:
if (n & 1) == 0:
freq[n] += 1
if freq:
high = max(freq.values())
for f in sorted(freq):
if freq[f] == high:
return f
return -1
Difficulty
and has an acceptance rate of about 54% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Counting
- Hash Table
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 defines a method that receives a list of integers and returns the even number that appears most frequently. If the input contains no even numbers, the method yields -1. The algorithm proceeds in three logical phases: counting occurrences of even values, determining the highest occurrence count, and selecting the smallest even number that attains this count. Throughout the code, Python’s built-in data structures and language features are leveraged to keep the solution concise and efficient.
Frequency Counting
The first phase builds a frequency map that records how many times each even integer occurs.
freq = defaultdict(int)
for n in nums:
if (n & 1) == 0:
freq[n] += 1
A defaultdict initialized with int supplies a default count of zero, eliminating the need for explicit existence checks before incrementing. The condition (n & 1) == 0 uses a bitwise AND to test evenness, which is marginally faster than the arithmetic modulo operation. Only numbers that satisfy this test are inserted into the map, ensuring that the dictionary contains exclusively even keys.
Determining the Maximum Frequency
After the counting loop, the code checks whether any even numbers were recorded.
if freq:
high = max(freq.values())
The truthiness of freq confirms that at least one even integer was encountered. The call to max on the dictionary’s values extracts the greatest occurrence count, stored in high. This step isolates the target frequency without scanning the entire dictionary again later.
Selecting the Smallest Even Number with the Maximum Frequency
With the maximum count known, the algorithm iterates over the dictionary’s keys in sorted order.
for f in sorted(freq):
if freq[f] == high:
return f
Sorting the keys guarantees that the first key whose frequency matches high is the smallest such even number, satisfying the problem’s tie-breaking rule. The immediate return exits the method as soon as the correct value is found, avoiding unnecessary further comparisons.
Edge Cases Handled
When the input list is empty, the counting loop never executes, leaving freq empty. The subsequent if freq: guard fails, and the method proceeds to the final return statement, yielding -1.
If the list contains only odd numbers, the evenness test never succeeds, so freq remains empty and the same fallback path returns -1.
When multiple even numbers share the highest frequency, the sorted iteration ensures that the smallest among them is chosen, adhering to the required deterministic selection.
If a single even number appears repeatedly, the dictionary holds a single entry; high equals that entry’s count, and the sorted loop returns the sole key instantly.
Performance Optimizations Observed
The use of a defaultdict removes conditional branches that would otherwise be needed to initialize dictionary entries, reducing overhead per iteration.
Employing a bitwise operation for evenness checks avoids the relatively slower modulo operation, offering a micro-optimization that accumulates over large inputs.
Computing the maximum frequency once with max(freq.values()) prevents repeated scans of the frequency map during the selection phase.
Sorting only the dictionary’s keys, rather than the entire (key, value) pairs, minimizes the amount of data processed by the sorting algorithm.
Finally, the early return inside the sorted loop stops further iteration as soon as the answer is identified, preventing needless work when the smallest qualifying even number appears early in the sorted order.
ELI5 - Simplified Explanation
Imagine a big bucket full of different number blocks. The goal is to find which even number shows up the most often in that bucket.
First, a tiny box is set aside to act as a tally sheet. The code looks at every single block in the bucket one by one. It checks to see if the number is even, which is like checking if a block has a matching pair so it can be split into two equal piles. If the block is even, it goes onto the tally sheet and gets a checkmark next to its name.
Once every block has been checked, the tally sheet is looked over to see which number has the most checkmarks. If there is a tie where a few numbers have the same highest amount of checkmarks, the code picks the smallest number among those winners. If the bucket was empty or had no even numbers at all, the code simply says there is no answer to be found.
Code Quality
Complexity Analysis
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 | Python | Java | C++ | TS | ||||||
| WalkCCC | Python | Java | C++ | ||||||||
| leetcode.ca | Python | Java | Go | C++ | PHP | Rust | TS | ||||
| Progiez | Python | Java | C++ | ||||||||
| github | chandansgowda | Python | |||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| shreymehul | C# | ||||||||||
| varunu28 | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| shreymehul | C# | ||||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 451: Sort Characters By Frequency
Solved On The Same Day
- problem 1184: Distance Between Bus Stops
- problem 1342: Number of Steps to Reduce a Number to Zero
- problem 1399: Count Largest Group
- problem 1496: Path Crossing
- problem 1646: Get Maximum in Generated Array
- problem 1893: Check if All the Integers in a Range Are Covered
- problem 2432: The Employee That Worked on the Longest Task
- problem 2451: Odd String Difference
- problem 2540: Minimum Common Value
- problem 609: Find Duplicate File in System
- problem 1169: Invalid Transactions
- problem 1711: Count Good Meals
- problem 1781: Sum of Beauty of All Substrings
- problem 1865: Finding Pairs With a Certain Sum
- problem 1871: Jump Game VII
- problem 2013: Detect Squares
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