Facebook Pixel

2404. Most Frequent Even Element

EasyArrayHash TableCounting
Leetcode Link

Problem Description

You are given an integer array nums. Your task is to find the most frequently occurring even element in the array.

The problem has the following rules:

  • You need to return the even element that appears the most times in the array
  • If multiple even elements have the same highest frequency (a tie), return the smallest one among them
  • If there are no even elements in the array at all, return -1

For example:

  • If nums = [0, 1, 2, 2, 4, 4, 1], the even elements are [0, 2, 2, 4, 4]. The element 2 appears 2 times and 4 appears 2 times (tied for most frequent), so we return 2 (the smaller value).
  • If nums = [1, 3, 5], there are no even elements, so we return -1.

The solution uses a hash table to count occurrences of even elements. It filters the array to keep only even numbers (where x % 2 == 0), counts their frequencies using Counter, then iterates through the counts to find the element with maximum frequency. When frequencies are equal, it chooses the smaller element value.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

To find the most frequent even element, we need to track two things: which elements are even and how many times each appears. This naturally leads us to think about using a frequency counter.

The key insight is that we can break this problem into smaller steps:

  1. First, filter out only the even numbers (since odd numbers don't matter for our answer)
  2. Count how many times each even number appears
  3. Find the one with the highest count

A hash table (or Counter in Python) is perfect for counting frequencies because it allows us to map each unique even number to its count in O(1) time per operation.

When we iterate through our frequency map to find the answer, we need to handle the tie-breaking rule. We maintain two variables: ans for the current best answer and mx for its frequency. As we check each even number and its count, we update our answer in two cases:

  • When we find a number with higher frequency (v > mx)
  • When we find a number with the same frequency but smaller value (v == mx and ans > x)

This approach ensures we always keep track of the most frequent even element, and in case of ties, we automatically get the smallest one. Starting with ans = -1 handles the edge case where no even elements exist - if we never update ans, we return -1 as required.

Solution Approach

The solution uses a hash table to efficiently count and track even elements. Here's how the implementation works:

Step 1: Filter and Count Even Elements

cnt = Counter(x for x in nums if x % 2 == 0)

We use Python's Counter from the collections module to create a frequency map. The generator expression (x for x in nums if x % 2 == 0) filters the array on-the-fly, keeping only even numbers. The condition x % 2 == 0 checks if a number is even. This creates a hash table where keys are even numbers and values are their frequencies.

Step 2: Initialize Tracking Variables

ans, mx = -1, 0

We initialize two variables:

  • ans = -1: Stores the current best answer (defaulting to -1 for the case when no even elements exist)
  • mx = 0: Tracks the maximum frequency found so far

Step 3: Find the Most Frequent Even Element

for x, v in cnt.items():
    if v > mx or (v == mx and ans > x):
        ans, mx = x, v

We iterate through each even number x and its frequency v in the hash table. We update our answer when:

  • The current frequency v is greater than the maximum frequency mx we've seen (found a more frequent element)
  • The current frequency v equals mx but the current number x is smaller than our current answer ans (tie-breaking rule)

When either condition is met, we update both ans to the current number and mx to its frequency.

Step 4: Return the Result

return ans

After checking all even elements, ans contains either the most frequent even element (with ties broken by smallest value) or -1 if no even elements were found.

The time complexity is O(n) where n is the length of the input array, and the space complexity is O(k) where k is the number of unique even elements.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with nums = [4, 2, 6, 2, 4, 4, 8].

Step 1: Filter and Count Even Elements

All numbers in this array are even, so our Counter will include all of them:

  • 4 appears 3 times
  • 2 appears 2 times
  • 6 appears 1 time
  • 8 appears 1 time

Our hash table cnt becomes: {4: 3, 2: 2, 6: 1, 8: 1}

Step 2: Initialize Tracking Variables

We start with ans = -1 and mx = 0.

Step 3: Find the Most Frequent Even Element

Now we iterate through the hash table:

First iteration: x = 4, v = 3

  • Is v > mx? Yes, 3 > 0
  • Update: ans = 4, mx = 3

Second iteration: x = 2, v = 2

  • Is v > mx? No, 2 < 3
  • Is v == mx and ans > x? No, 2 ≠ 3
  • No update

Third iteration: x = 6, v = 1

  • Is v > mx? No, 1 < 3
  • Is v == mx and ans > x? No, 1 ≠ 3
  • No update

Fourth iteration: x = 8, v = 1

  • Is v > mx? No, 1 < 3
  • Is v == mx and ans > x? No, 1 ≠ 3
  • No update

Step 4: Return the Result

We return ans = 4, which is the most frequent even element with 3 occurrences.

Let's also consider a tie-breaking scenario with nums = [2, 2, 4, 4, 6]:

  • Counter: {2: 2, 4: 2, 6: 1}
  • After processing 2: ans = 2, mx = 2
  • When processing 4: v == mx (both are 2) but ans < x (2 < 4), so no update
  • When processing 6: frequency is lower, no update
  • Returns 2 (smallest among tied elements)

Solution Implementation

1from typing import List
2from collections import Counter
3
4class Solution:
5    def mostFrequentEven(self, nums: List[int]) -> int:
6        # Count frequency of each even number in the array
7        frequency_map = Counter(num for num in nums if num % 2 == 0)
8      
9        # Initialize result and maximum frequency
10        result = -1
11        max_frequency = 0
12      
13        # Iterate through each even number and its frequency
14        for number, frequency in frequency_map.items():
15            # Update result if:
16            # 1. Current frequency is greater than max frequency, OR
17            # 2. Current frequency equals max frequency AND current number is smaller
18            if frequency > max_frequency or (frequency == max_frequency and number < result):
19                result = number
20                max_frequency = frequency
21      
22        # Return the most frequent even number (or -1 if no even numbers exist)
23        return result
24
1class Solution {
2    public int mostFrequentEven(int[] nums) {
3        // HashMap to store the frequency count of even numbers
4        Map<Integer, Integer> frequencyMap = new HashMap<>();
5      
6        // Count the frequency of each even number in the array
7        for (int number : nums) {
8            if (number % 2 == 0) {
9                // If the number is even, increment its count in the map
10                frequencyMap.merge(number, 1, Integer::sum);
11            }
12        }
13      
14        // Initialize variables to track the result and maximum frequency
15        int result = -1;
16        int maxFrequency = 0;
17      
18        // Iterate through the frequency map to find the most frequent even number
19        for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
20            int currentNumber = entry.getKey();
21            int currentFrequency = entry.getValue();
22          
23            // Update result if we find a number with higher frequency
24            // or same frequency but smaller value (to get the smallest number in case of tie)
25            if (maxFrequency < currentFrequency || 
26                (maxFrequency == currentFrequency && result > currentNumber)) {
27                result = currentNumber;
28                maxFrequency = currentFrequency;
29            }
30        }
31      
32        // Return the most frequent even number, or -1 if no even number exists
33        return result;
34    }
35}
36
1class Solution {
2public:
3    int mostFrequentEven(vector<int>& nums) {
4        // HashMap to store frequency of each even number
5        unordered_map<int, int> frequencyMap;
6      
7        // Count frequency of even numbers only
8        for (int num : nums) {
9            if (num % 2 == 0) {
10                ++frequencyMap[num];
11            }
12        }
13      
14        // Initialize result as -1 (default when no even number exists)
15        // maxFrequency tracks the highest frequency found so far
16        int result = -1;
17        int maxFrequency = 0;
18      
19        // Iterate through the frequency map to find the most frequent even number
20        // If there's a tie in frequency, choose the smaller number
21        for (auto& [number, frequency] : frequencyMap) {
22            if (maxFrequency < frequency || 
23                (maxFrequency == frequency && result > number)) {
24                result = number;
25                maxFrequency = frequency;
26            }
27        }
28      
29        return result;
30    }
31};
32
1/**
2 * Finds the most frequent even number in an array.
3 * If multiple even numbers have the same highest frequency, returns the smallest one.
4 * Returns -1 if no even numbers exist in the array.
5 * 
6 * @param nums - The input array of numbers
7 * @returns The most frequent even number, or -1 if no even numbers exist
8 */
9function mostFrequentEven(nums: number[]): number {
10    // Map to store frequency count of each even number
11    const frequencyMap: Map<number, number> = new Map();
12  
13    // Count frequency of each even number
14    for (const num of nums) {
15        if (num % 2 === 0) {
16            // Increment count for this even number (default to 0 if not exists)
17            frequencyMap.set(num, (frequencyMap.get(num) ?? 0) + 1);
18        }
19    }
20  
21    // Initialize result and maximum frequency
22    let result = -1;
23    let maxFrequency = 0;
24  
25    // Find the even number with highest frequency (smallest if tie)
26    for (const [evenNumber, frequency] of frequencyMap) {
27        // Update result if:
28        // 1. Current frequency is higher than max frequency, OR
29        // 2. Current frequency equals max frequency AND current number is smaller
30        if (maxFrequency < frequency || (maxFrequency === frequency && result > evenNumber)) {
31            result = evenNumber;
32            maxFrequency = frequency;
33        }
34    }
35  
36    return result;
37}
38

Time and Space Complexity

The time complexity is O(n), where n is the length of the input array nums. This is because:

  • The list comprehension x for x in nums if x % 2 == 0 iterates through all n elements once to filter even numbers
  • Creating the Counter from the filtered elements takes O(k) time where k is the number of even elements (at most n)
  • Iterating through cnt.items() takes O(k) time where k is the number of unique even elements
  • Overall, the dominant operation is the initial iteration through all n elements

The space complexity is O(n) in the worst case. This occurs when:

  • The Counter object cnt stores at most n/2 unique even elements if all elements in the array are distinct even numbers
  • The list comprehension creates a temporary filtered list that could contain up to n elements if all numbers are even
  • Therefore, the space requirement scales linearly with the input size n

Learn more about how to find time and space complexity quickly.

Common Pitfalls

Pitfall 1: Forgetting to Handle the Tie-Breaking Rule Correctly

A common mistake is to only check for maximum frequency without properly handling ties. Developers might write:

# INCORRECT - doesn't handle ties properly
for number, frequency in frequency_map.items():
    if frequency > max_frequency:  # Missing tie-breaking logic
        result = number
        max_frequency = frequency

This fails when multiple even numbers have the same highest frequency. For example, with nums = [2, 2, 4, 4], both 2 and 4 appear twice. The incorrect code would return whichever number appears last in the hash table iteration (which is unpredictable), rather than consistently returning 2 (the smaller value).

Solution: Always include the tie-breaking condition (frequency == max_frequency and number < result) to ensure the smallest number is selected when frequencies are equal.

Pitfall 2: Incorrect Initial Value for Result Variable

Another mistake is initializing the result variable to 0 or a positive number:

# INCORRECT - wrong initial value
result = 0  # Should be -1
max_frequency = 0

This causes problems when the array contains no even elements. The function would incorrectly return 0 instead of -1, suggesting that 0 is the most frequent even element when it doesn't exist in the array at all.

Solution: Always initialize result = -1 to handle the edge case where no even elements exist in the array.

Pitfall 3: Using Dictionary Instead of Counter Incorrectly

Some developers might try to manually build a frequency dictionary without proper initialization:

# INCORRECT - KeyError risk
frequency_map = {}
for num in nums:
    if num % 2 == 0:
        frequency_map[num] += 1  # KeyError if num not in dictionary

This raises a KeyError when encountering an even number for the first time.

Solution: Either use Counter which handles initialization automatically, or properly check if the key exists:

frequency_map = {}
for num in nums:
    if num % 2 == 0:
        frequency_map[num] = frequency_map.get(num, 0) + 1
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

How many ways can you arrange the three letters A, B and C?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More