Skip to main content
Back to problems
#2404
Easy Algorithms

Most frequent even element

Array Hash Table Counting
53.3% acceptance
Feb 25, 2026
1116
41
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.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;

impl Solution {
  pub fn most_frequent_even(nums: Vec<i32>) -> i32 {
    let mut freq: HashMap<i32, i32> = HashMap::new();
    for &n in &nums {
      if n % 2 == 0 {
        *freq.entry(n).or_insert(0) += 1;
      }
    }
    if freq.is_empty() {
      return -1;
    }
    let max_freq = *freq.values().max().unwrap();
    let mut candidates: Vec<i32> = freq
      .into_iter()
      .filter(|&(_, v)| v == max_freq)
      .map(|(k, _)| k)
      .collect();
    candidates.sort();
    candidates[0]
  }
}