EasyNo. 2404

Most Frequent Even Element — LeetCode 2404 Python Solution

Pattern
Hash Map
Topics
Array, Hash Table, Counting
Reading time
2 min

The problem

Given an integer array nums, return the most frequent even element. If there is a tie, return the smallest one.

Example

Input
nums = [0,1,2,2,4,4,1]
Output
2
Explanation
The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most.

Python solution

PythonSolution
class Solution:
    def mostFrequentEven(self, nums: List[int]) -> int:
        cnt = Counter(x for x in nums if x % 2 == 0)
        ans, mx = -1, 0
        for x, v in cnt.items():
            if v > mx or (v == mx and ans > x):
                ans, mx = x, v
        return ans

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2404. Most Frequent Even Element is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0169Majority ElementEasy
0229Majority Element IIMedium
0347Top K Frequent ElementsMedium
0594Longest Harmonious SubsequenceEasy
0621Task SchedulerMedium
0692Top K Frequent WordsMedium

Frequently asked questions

How hard is LeetCode 2404. Most Frequent Even Element?

LeetCode 2404. Most Frequent Even Element is rated Easy on LeetCode.

What is the time complexity of LeetCode 2404. Most Frequent Even Element?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 2404. Most Frequent Even Element?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 2404. Most Frequent Even Element cover?

LeetCode 2404. Most Frequent Even Element is tagged Array, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.