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
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.
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
:
%
).Counter
or collections.defaultdict
). Other languages may require using get()
with a default value or a try-except
block to handle potential KeyError
exceptions.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
.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).