Leetcode 2404. Most Frequent Even Element
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
.
Q: What is the range of input values for nums
?
A: The input array nums
can contain integers ranging from -10^5
to 10^5
.
Q: What is the length of the input array nums
?
A: The length of nums
can be between 1
and 10^5
.
Q: How should we handle negative even numbers? A: Negative even numbers are considered valid and should be treated like any other even number.
Q: Can nums
contain duplicates?
A: Yes, nums
can contain duplicate values.
nums
:
-1
.import java.util.HashMap;
import java.util.Map;
public class Solution {
public int mostFrequentEvenElement(int[] nums) {
Map<Integer, Integer> frequencyMap = new HashMap<>();
// Step 2: Populate the frequency map with even numbers
for (int num : nums) {
if (num % 2 == 0) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
}
// Step 3: Find the most frequent even element
int mostFrequentEven = -1;
int highestFrequency = -1;
for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
int num = entry.getKey();
int freq = entry.getValue();
if (freq > highestFrequency || (freq == highestFrequency && num < mostFrequentEven)) {
highestFrequency = freq;
mostFrequentEven = num;
}
}
return mostFrequentEven;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = { 4, 2, 4, 6, 2, 4, 2 };
System.out.println(solution.mostFrequentEvenElement(nums)); // Output: 2
}
}
nums
.nums
.Overall, the time complexity is O(n + m), which simplifies to O(n) since m is at most n.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?