{x}
blog image

Most Frequent Even Element

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.

 

Example 1:

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:

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

Example 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] <= 105

Solution Explanation: Finding the Most Frequent Even Number

The problem asks to find the most frequent even number in an array. If multiple even numbers have the same highest frequency, we return the smallest one. If no even numbers exist, we return -1.

Approach: Hash Table (Frequency Counting)

The most efficient approach uses a hash table (or dictionary in Python) to count the occurrences of each even number. We iterate through the input array nums:

  1. Even Number Check: For each number, we check if it's even using the modulo operator (%).
  2. Frequency Count: If it's even, we increment its count in the hash table. If the number isn't already in the hash table, we add it with a count of 1. Languages like Python offer convenient ways to do this (e.g., Counter or collections.defaultdict). Other languages may require using get() with a default value or a try-except block to handle potential KeyError exceptions.
  3. Finding the Most Frequent: After iterating through the entire array, we iterate through the hash table to find the even number with the highest frequency. We keep track of both the most frequent number (ans) and its frequency (mx). If we encounter a number with a higher frequency, or a number with the same frequency but a smaller value, we update ans and mx.

Time and Space Complexity

  • Time Complexity: O(n), where n is the length of the input array. We iterate through the array once to count frequencies and then iterate through the hash table (whose size is at most n). Both iterations take linear time.
  • Space Complexity: O(k), where k is the number of unique even numbers in the array. In the worst case, k could be as large as n (if all numbers are unique and even), but it's often much smaller. The space used is dominated by the hash table to store the frequencies.

Code Examples (with explanations)

Python:

from collections import Counter
 
class Solution:
    def mostFrequentEven(self, nums: List[int]) -> int:
        cnt = Counter(x for x in nums if x % 2 == 0) #Efficiently counts even numbers
        ans, mx = -1, 0  #Initialize answer and maximum frequency
        for x, v in cnt.items():  #Iterate through the even number counts
            if v > mx or (v == mx and ans > x): #Check for higher frequency or smaller value with same frequency
                ans, mx = x, v #Update answer and maximum frequency
        return ans

Java:

import java.util.HashMap;
import java.util.Map;
 
class Solution {
    public int mostFrequentEven(int[] nums) {
        Map<Integer, Integer> cnt = new HashMap<>();
        for (int x : nums) {
            if (x % 2 == 0) {
                cnt.put(x, cnt.getOrDefault(x, 0) + 1); //Handles cases where a number might not exist yet
            }
        }
        int ans = -1, mx = 0;
        for (Map.Entry<Integer, Integer> entry : cnt.entrySet()) {
            int x = entry.getKey(), v = entry.getValue();
            if (v > mx || (v == mx && ans > x)) {
                ans = x;
                mx = v;
            }
        }
        return ans;
    }
}

The Java and other language examples follow a similar structure, adapting the hash table handling and comparison logic to the specific language's syntax and libraries. The core algorithm remains the same: count even numbers, then find the most frequent one (with a tie-breaker for the smallest value).