Skip to content

2404. Most Frequent Even Element 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int mostFrequentEven(vector<int>& nums) {
    int ans = -1;
    unordered_map<int, int> count;

    for (const int num : nums) {
      if (num % 2 == 1)
        continue;
      const int newCount = ++count[num];
      const int maxCount = count[ans];
      if (newCount > maxCount || newCount == maxCount && num < ans)
        ans = num;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int mostFrequentEven(int[] nums) {
    int ans = -1;
    Map<Integer, Integer> count = new HashMap<>();

    for (final int num : nums) {
      if (num % 2 == 1)
        continue;
      final int newCount = count.merge(num, 1, Integer::sum);
      final int maxCount = count.getOrDefault(ans, 0);
      if (newCount > maxCount || newCount == maxCount && num < ans)
        ans = num;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def mostFrequentEven(self, nums: list[int]) -> int:
    ans = -1
    count = collections.Counter()

    for num in nums:
      if num % 2 == 1:
        continue
      count[num] += 1
      newCount = count[num]
      maxCount = count[ans]
      if newCount > maxCount or newCount == maxCount and num < ans:
        ans = num

    return ans