Watch 10 video solutions for Most Frequent Even Element, a easy level problem involving Array, Hash Table, Counting. This walkthrough by Bro Coders has 2,943 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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.
Example 1:
Input: nums = [0,1,2,2,4,4,1] Output: 2 Explanation: The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most. We return the smallest one, which is 2.
Example 2:
Input: nums = [4,4,4,9,2,4] Output: 4 Explanation: 4 is the even element appears the most.
Example 3:
Input: nums = [29,47,21,41,13,37,25,7] Output: -1 Explanation: There is no even element.
Constraints:
1 <= nums.length <= 20000 <= nums[i] <= 105Problem Overview: You are given an integer array and must return the even number that appears most frequently. If multiple even numbers share the same frequency, return the smallest one. If the array contains no even numbers, return -1.
Approach 1: Using HashMap to Count Frequencies (O(n) time, O(k) space)
Traverse the array once and track the frequency of each even number using a hash map. For every element, check num % 2 == 0 and increment its count in the map. After building the frequency table, iterate through the stored entries to find the number with the highest frequency, breaking ties by choosing the smaller value. Hash lookups and updates run in constant time, so the full scan stays linear. This approach works well for general cases and directly models the problem as a frequency counting task using a hash table.
Approach 2: Sorting and Counting Consecutive Elements (O(n log n) time, O(1) extra space)
First sort the array so identical values become consecutive. Then iterate through the sorted array while counting streaks of the same even number. When the value changes, compare the current streak length with the best frequency seen so far and update the result if needed. Sorting groups duplicates together, which makes counting simple without extra data structures. This approach trades additional time for minimal memory and relies mainly on array traversal and sequential counting.
Recommended for interviews: The hash map counting approach is typically expected. It runs in O(n) time and clearly demonstrates frequency tracking using a hash table. The sorting approach still works but is slower due to the O(n log n) sort step. Showing the counting logic first and then optimizing with a hash map demonstrates strong problem‑solving progression.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| HashMap Frequency Counting | O(n) | O(k) | General case when you want the fastest linear scan solution |
| Sorting + Consecutive Counting | O(n log n) | O(1) extra (depending on sort) | When avoiding extra hash map memory or when the array is already sorted |