#2404
Most Frequent Even Element
EasyArrayHash TableCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a hash map allows us to count occurrences of each even number in a single pass through the array, making the solution much more efficient.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a hash map to store the frequency of each even number.
- 2Step 2: Loop through the array and for each even number, increment its count in the hash map.
- 3Step 3: After populating the hash map, initialize variables to track the maximum frequency and the smallest even number.
- 4Step 4: Loop through the hash map to find the most frequent even number, considering ties by choosing the smaller number.
- 5Step 5: Return the result or -1 if no even number was found.
solution.py18 lines
1# Full working Python code
2
3def most_frequent_even(nums):
4 freq_map = {}
5 for num in nums:
6 if num % 2 == 0:
7 if num in freq_map:
8 freq_map[num] += 1
9 else:
10 freq_map[num] = 1
11 max_freq = 0
12 result = -1
13 for num, count in freq_map.items():
14 if count > max_freq or (count == max_freq and num < result):
15 max_freq = count
16 result = num
17 return result
18ℹ
Complexity note: The time complexity is O(n) because we traverse the array once to build the frequency map and then once to find the most frequent even number. The space complexity is O(n) due to the hash map storing the counts.
- 1Using a hash map allows for efficient counting of elements.
- 2When dealing with ties, always consider the smallest element.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.