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] <= 105This approach involves using a hash map or dictionary to count the frequency of each even number. We then iterate through the hash map to find the even number with the highest frequency, choosing the smallest one in case of a tie.
The code uses an array as a frequency map to count occurrences of each even element. We iterate over `nums`, update the frequency of even numbers, and track the maximum frequency and the smallest even number when frequencies match. Finally, the smallest number with the highest frequency is returned.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the array because we iterate through the array once.
Space Complexity: O(100001), which is O(1) in constant space for a fixed-size array.
This approach involves sorting the array. After sorting, we iterate through the array and count consecutive even numbers, keeping track of the most frequent one. This method takes advantage of the sorting to make the counting simpler once elements are organized.
This C solution first sorts the array to organize the numbers. It then iterates over the sorted array, counting consecutive even numbers to determine which one appears most frequently. The condition checks whether to update the most frequent even number considering current frequency.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n log n) due to sorting, where n is the number of elements.
Space Complexity: O(1) additional space since we sort in place.
| Approach | Complexity |
|---|---|
| Using HashMap to Count Frequencies | Time Complexity: O(n), where n is the length of the array because we iterate through the array once. |
| Sorting and Counting Consecutive Elements | Time Complexity: O(n log n) due to sorting, where n is the number of elements. |
Top K Frequent Elements - Bucket Sort - Leetcode 347 - Python • NeetCode • 665,789 views views
Watch 9 more video solutions →Practice Most Frequent Even Element with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor