Problem 2404

Abstract / Summary

Find the even number that appears most often in the list and return it if it occurs more than once.

Note

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

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
14 lines | 374 bytes | submitted December 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 54% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Counting
  • Hash Table
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

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

Complexity Analysis

not analyzed yet

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 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
27 links | 14 authors | 10 languages

Videos

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

Similar Problems

1 similar problem

Solved On The Same Day

17 solutions   December 12, 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