Problem

Given an integer array nums, return the most frequent even element.

If there is a tie, return the smallest one. If there is no such element, return -1.

Examples

Example 1

1
2
3
4
5
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.
We return the smallest one, which is 2.

Example 2

1
2
3
Input: nums = [4,4,4,9,2,4]
Output: 4
Explanation: 4 is the even element appears the most.

Example 3

1
2
3
Input: nums = [29,47,21,41,13,37,25,7]
Output: -1
Explanation: There is no even element.

Constraints

  • 1 <= nums.length <= 2000
  • 0 <= nums[i] <= 10^5

Solution

Method 1 - Hash Map Counting

Intuition

Count the frequency of each even element. The answer is the even element with the highest frequency; if there is a tie, return the smallest one. If no even element exists, return -1.

Approach

Iterate through the array, count frequencies of even numbers, and select the most frequent (smallest in case of tie).

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import java.util.*;
class Solution {
    public int mostFrequentEven(int[] nums) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int x : nums) {
            if (x % 2 == 0) count.put(x, count.getOrDefault(x, 0) + 1);
        }
        int ans = -1, max = 0;
        for (int k : count.keySet()) {
            int v = count.get(k);
            if (v > max || (v == max && k < ans) || ans == -1) {
                max = v;
                ans = k;
            }
        }
        return ans;
    }
}
1
2
3
4
5
6
7
def mostFrequentEven(nums):
    from collections import Counter
    count = Counter(x for x in nums if x % 2 == 0)
    if not count:
        return -1
    max_freq = max(count.values())
    return min(x for x in count if count[x] == max_freq)

Complexity

  • ⏰ Time complexity: O(n) — One pass to count, one pass to select answer.
  • 🧺 Space complexity: O(n) — For the count map.