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: [0,1,2,2,5,4,4,6]01225446evenoddevenevenoddevenevenevenEven Numbers Frequency:0: 1 time2: 2 times4: 2 times6: 1 timeMaximum frequency = 2 (tie between 2 and 4)Winner: 2 (smaller value breaks tie)Result: 2
Understanding the Visualization
1
Input Array
Array with mix of odd and even numbers
2
Filter & Count
Count frequencies of even numbers only
3
Find Winner
Most frequent even number (smallest for ties)
Key Takeaway
🎯 Key Insight: Count only even numbers and use smallest value to break frequency ties
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