Problem Description
Given an integer array nums, return the most frequent even element. If there is a tie, return the smallest even element. If no even element exists, return -1.
Key Insights
- Use a hash table to count the frequency of even numbers.
- Ignore odd numbers during the counting process.
- Determine the most frequent even number; in the case of a tie, select the smallest even number.
- Return -1 if no even number is found.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(n), for storing the count of even numbers in the worst case.
Solution
The solution iterates through the array once to count the occurrences of each even number using a hash table (or dictionary). After counting, it iterates over the hash table to find the even number with the highest frequency. If multiple even numbers have the same frequency, the smallest one is chosen. If no even number is encountered, the solution returns -1.