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:
  • ๐Ÿ† 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
๐Ÿ—ณ๏ธ Student Council ElectionOnly Even ID Students Can Run for PresidentCandidate #0๐ŸŽ“Votes: 1Status: EligibleCandidate #2๐Ÿ‘‘Votes: 2 โ† WINNER!Status: EligibleCandidate #4๐ŸŽ“Votes: 2 (tie)Status: EligibleStudent #1โŒNot Eligible(Odd ID)๐Ÿ† Election ResultsBallot Count: [0, 1, 2, 2, 4, 4, 1]Even ID Candidates: 0(1 vote), 2(2 votes), 4(2 votes)Winner: Candidate #2 (most votes, smallest ID in tie-breaker)Algorithm: Hash table to count votes in O(n) time!๐Ÿ’ก Algorithm Insightโ€ข One-Pass Solution: Count votes and track winner simultaneouslyโ€ข Hash Table: O(1) vote counting and lookupโ€ข Tie-Breaking: Always prefer the candidate with smaller ID number
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!
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 18
28.5K Views
Medium Frequency
~15 min Avg. Time
1.2K 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