Most Frequent Even Element - 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.

Input & Output

Example 1 — Basic Case with Tie
$ Input: nums = [0,1,2,2,5,4,4,6]
Output: 2
💡 Note: Even numbers: 0(1×), 2(2×), 4(2×), 6(1×). Both 2 and 4 appear twice, but 2 < 4, so return 2.
Example 2 — Clear Winner
$ Input: nums = [4,4,4,9,2,4]
Output: 4
💡 Note: Even numbers: 4(4×), 2(1×). 4 appears most frequently, so return 4.
Example 3 — No Even Numbers
$ Input: nums = [29,47,21,41,13,37,25,7]
Output: -1
💡 Note: All numbers are odd, so there are no even elements to return.

Constraints

  • 1 ≤ nums.length ≤ 2000
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Most Frequent Even Element INPUT nums = [0,1,2,2,5,4,4,6] 0 1 2 2 5 4 4 6 0 1 2 3 4 5 6 7 Legend: Even (freq 2) Even (freq 2) Even (freq 1) Odd (skip) Even Numbers Found: 0, 2, 2, 4, 4, 6 ALGORITHM (Hash Map) 1 Initialize Hash Map Count even numbers only 2 Iterate Array if num % 2 == 0: count++ 3 Find Max Frequency Track highest count 4 Handle Ties Return smallest if tie Hash Map Result: Key Count 0 1 2 2 4 2 6 1 2 and 4 both have count=2 Return smaller: 2 FINAL RESULT Most Frequent Even Element 2 Output: 2 Why 2? - Even numbers: 0,2,4,6 - Frequency of 2: 2 times - Frequency of 4: 2 times - Tie! Pick smaller: 2 < 4 OK - Verified Key Insight: Use a hash map to count frequency of even numbers in O(n) time. When multiple numbers have the same max frequency, track the smallest one. Return -1 if no even numbers exist. TutorialsPoint - Most Frequent Even Element | Hash Map Approach
Asked in
Facebook 15 Google 12
12.5K Views
Medium Frequency
~15 min Avg. Time
285 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen