Most Frequent Even Element — Easy Problem & Solution
Return the most frequent even element of nums. If several even elements tie, return the smallest of them. If there is no even element, return -1.
- Difficulty: Easy
- Topics: Arrays, Hash Table, Counting
- Asked at: Amazon, Google, Infosys
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Return the most frequent even element of nums. If several even elements tie, return the smallest of them. If there is no even element, return -1.
Example 1
Input: nums = [0,1,2,2,4,4,1]
Output: 2
Explanation: `2` and `4` both appear twice; `2` is smaller.
Example 2
Input: nums = [4,4,4,9,2,4]
Output: 4
Explanation: `4` appears four times.
Example 3
Input: nums = [29,47,21,41,13,37,25,7]
Output: -1
Explanation: No even element at all.
Constraints
1 <= nums.length <= 20000 <= nums[i] <= 10^5
How to solve Most Frequent Even Element
Tally the even elements, then pick the entry with the largest count, breaking ties toward the smaller value.
Approach
- Walk
nums, incrementing a counter for each even value. - Walk the counters, keeping the value with the highest count and, on equal counts, the smaller value.
- Return
-1if nothing was counted.
Why it works
The tie-break has to be checked explicitly — iterating a hash map gives no useful order, so "first seen with this count" is not the same as "smallest". Scanning candidates in ascending value order is the other way to get it right, and is why a sorted map or an array indexed by value is a natural fit here.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- 0 is even and a perfectly valid answer.
- The tie-break is by value, not by position.
-1means "no even element", not "no repeat".
Reference solution
Python
from collections import Counter
from typing import List
def mostFrequentEven(nums: List[int]) -> int:
counts = Counter(v for v in nums if v % 2 == 0)
best, best_count = -1, 0
for v, c in counts.items():
if c > best_count or (c == best_count and v < best):
best, best_count = v, c
return bestJavaScript
var mostFrequentEven = function(nums) {
var counts = {}, i;
for (i = 0; i < nums.length; i++) {
if (nums[i] % 2 !== 0) continue;
var key = String(nums[i]);
counts[key] = (counts[key] === undefined ? 0 : counts[key]) + 1;
}
var best = -1, bestCount = 0;
var keys = Object.keys(counts);
for (i = 0; i < keys.length; i++) {
var v = parseInt(keys[i], 10);
var c = counts[keys[i]];
if (c > bestCount || (c === bestCount && v < best)) { best = v; bestCount = c; }
}
return best;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.