Most Frequent Even Element - Problem
Find the Champion Even Number!
You're given an array of integers, and your mission is to find the most frequent even element. Think of it as a popularity contest, but only even numbers are allowed to participate!
The Rules:
Example: In
You're given an array of integers, and your mission is to find the most frequent even element. Think of it as a popularity contest, but only even numbers are allowed to participate!
The Rules:
- ๐ Return the even number that appears most frequently
- ๐ค If there's a tie, return the smallest even number among the tied winners
- โ If no even numbers exist in the array, return
-1
Example: In
[0, 1, 2, 2, 4, 4, 1], both 2 and 4 appear twice, but we return 2 because it's smaller! Input & Output
example_1.py โ Basic Case
$
Input:
[0,1,2,2,4,4,1]
โบ
Output:
2
๐ก Note:
The even elements are 0, 2, 2, 4, 4. Among these, both 2 and 4 appear twice. Since there's a tie, we return the smaller value, which is 2.
example_2.py โ Clear Winner
$
Input:
[4,4,4,9,2,4]
โบ
Output:
4
๐ก Note:
The even elements are 4, 4, 4, 2, 4. The element 4 appears 4 times while 2 appears only once. Therefore, 4 is the most frequent even element.
example_3.py โ No Even Elements
$
Input:
[29,47,21,41,13,37,25,7]
โบ
Output:
-1
๐ก Note:
There are no even elements in this array, so we return -1.
Constraints
- 1 โค nums.length โค 2000
- -105 โค nums[i] โค 105
- The array contains at least one integer
Visualization
Tap to expand
Understanding the Visualization
1
Eligibility Check
Only students with even ID numbers can participate (filter even elements)
2
Vote Counting
Count votes for each eligible candidate using a hash table
3
Declare Winner
The candidate with most votes wins. In case of tie, the one with smaller ID wins
4
Optimization
Instead of counting all votes first, we can track the current winner while counting!
Key Takeaway
๐ฏ Key Insight: We can optimize by tracking the current winner while counting, eliminating the need for a separate search phase. This transforms a two-pass algorithm into an elegant single-pass solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code