Talentd
FleetCode
Make and follow sheets.Sign in

Most Frequent Even Element solution and explanation

EasyArrayCountingHash Table4 min read54.0% acceptanceUpdated 9 Apr 2026
2404. Most Frequent Even Element | Leetcode Weekly Contest 310 | LeetCode 2404Bro Coders · 5:43 · 3K viewsWatch on YouTube
9 more videos on this problem
  1. 2404. Most Frequent Even Element | Leetcode Weekly Contest 310 | LeetCode 2404Bro Coders · 5:43 · 3K views
  2. Leetcode 2404 Most Frequent Even Element | Maps | Coding Decoded SDE SheetCoding Decoded · 3:13 · 1K views
  3. 2404. Most Frequent Even Element || leetcode Weekly 310 || Leetcode EasyBinaryMagic · 6:51 · 986 views
  4. 2404. Most Frequent Even Element | LEETCODE EASYcode Explainer · 3:56 · 966 views
  5. 2404. Most Frequent Even Element (Leetcode Easy)Programming Live with Larry · 2:38 · 759 views
  6. Leetcode 2404. Most Frequent Even ElementElite Code · 8:00 · 396 views
  7. Leetcode Weekly contest 310 - Easy- Most Frequent Even ElementPrakhar Agrawal · 8:27 · 380 views
  8. Weekly Contest 310 | Leetcode 2404, 2405, 2406 | Let's Practice TogetherLet's Practice Together · 19:48 · 284 views
  9. 2404. Most Frequent Even Element || Leetcode weekly contest 310 || C++ || Hindi ExplanationCS warriors · 7:18 · 225 views
  10. 2404. Most Frequent Even Element | Leetcode Weekly Contest 310 | LeetCode 2404Broken Coder · 3:43 · 197 views

The problem

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 <= 2000
  • 0 <= nums[i] <= 105

Approach overview

Problem Overview: You are given an integer array and must return the even number that appears most frequently. If multiple even numbers share the same frequency, return the smallest one. If the array contains no even numbers, return -1.

Approach 1: Using HashMap to Count Frequencies (O(n) time, O(k) space)

Traverse the array once and track the frequency of each even number using a hash map. For every element, check num % 2 == 0 and increment its count in the map. After building the frequency table, iterate through the stored entries to find the number with the highest frequency, breaking ties by choosing the smaller value. Hash lookups and updates run in constant time, so the full scan stays linear. This approach works well for general cases and directly models the problem as a frequency counting task using a hash table.

Approach 2: Sorting and Counting Consecutive Elements (O(n log n) time, O(1) extra space)

First sort the array so identical values become consecutive. Then iterate through the sorted array while counting streaks of the same even number. When the value changes, compare the current streak length with the best frequency seen so far and update the result if needed. Sorting groups duplicates together, which makes counting simple without extra data structures. This approach trades additional time for minimal memory and relies mainly on array traversal and sequential counting.

Recommended for interviews: The hash map counting approach is typically expected. It runs in O(n) time and clearly demonstrates frequency tracking using a hash table. The sorting approach still works but is slower due to the O(n log n) sort step. Showing the counting logic first and then optimizing with a hash map demonstrates strong problem‑solving progression.

Approach 1: Using HashMap to Count Frequencies

This 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.

def most_frequent_even(nums):
    freq = {}
    max_freq = 0
    smallest_even = -1

    for num in nums:
        if num % 2 == 0:
            freq[num] = freq.get(num, 0) + 1
            if freq[num] > max_freq or (freq[num] == max_freq and num < smallest_even):
                max_freq = freq[num]
                smallest_even = num

    return smallest_even

# Test case
print(most_frequent_even([0, 1, 2, 2, 4, 4, 1]))
import java.util.HashMap;
import java.util.Map;

public class Solution {
    public int mostFrequentEven(int[] nums) {
        Map<Integer, Integer> freq = new HashMap<>();
        int maxFreq = 0, smallestEven = -1;

        for (int num : nums) {
            if (num % 2 == 0) {
                freq.put(num, freq.getOrDefault(num, 0) + 1);
                if (freq.get(num) > maxFreq || (freq.get(num) == maxFreq && num < smallestEven)) {
                    maxFreq = freq.get(num);
                    smallestEven = num;
                }
            }
        }
        return smallestEven;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {0, 1, 2, 2, 4, 4, 1};
        System.out.println(solution.mostFrequentEven(nums));
    }
}
#include <iostream>
#include <vector>
#include <unordered_map>
#include <climits>
using namespace std;

int mostFrequentEven(vector<int>& nums) {
    unordered_map<int, int> freq;
    int maxFreq = 0, smallestEven = -1;
    for (int num : nums) {
        if (num % 2 == 0) {
            freq[num]++;
            if (freq[num] > maxFreq || (freq[num] == maxFreq && num < smallestEven)) {
                maxFreq = freq[num];
                smallestEven = num;
            }
        }
    }
    return smallestEven;
}

int main() {
    vector<int> nums = {0, 1, 2, 2, 4, 4, 1};
    cout << mostFrequentEven(nums) << endl;
    return 0;
}
function mostFrequentEven(nums) {
    let freq = {};
    let maxFreq = 0;
    let smallestEven = -1;

    for (let num of nums) {
        if (num % 2 === 0) {
            freq[num] = (freq[num] || 0) + 1;
            if (freq[num] > maxFreq || (freq[num] === maxFreq && num < smallestEven)) {
                maxFreq = freq[num];
                smallestEven = num;
            }
        }
    }
    return smallestEven;
}

console.log(mostFrequentEven([0, 1, 2, 2, 4, 4, 1]));
#include <stdio.h>
#include <limits.h>

int mostFrequentEven(int* nums, int numsSize) {
    int freq[100001] = {0};
    int maxFreq = 0;
    int smallestEven = -1;

    for (int i = 0; i < numsSize; i++) {
        if (nums[i] % 2 == 0) {
            freq[nums[i]]++;
            if (freq[nums[i]] > maxFreq || (freq[nums[i]] == maxFreq && nums[i] < smallestEven)) {
                maxFreq = freq[nums[i]];
                smallestEven = nums[i];
            }
        }
    }
    return smallestEven;
}

int main() {
    int nums[] = {0, 1, 2, 2, 4, 4, 1};
    int size = sizeof(nums) / sizeof(nums[0]);
    printf("%d\n", mostFrequentEven(nums, size));
    return 0;
}
using System;
using System.Collections.Generic;

public class Solution {
    public int MostFrequentEven(int[] nums) {
        Dictionary<int, int> freq = new Dictionary<int, int>();
        int maxFreq = 0, smallestEven = -1;

        foreach (int num in nums) {
            if (num % 2 == 0) {
                if (!freq.ContainsKey(num)) {
                    freq[num] = 0;
                }
                freq[num]++;
                if (freq[num] > maxFreq || (freq[num] == maxFreq && num < smallestEven)) {
                    maxFreq = freq[num];
                    smallestEven = num;
                }
            }
        }
        return smallestEven;
    }

    public static void Main() {
        Solution solution = new Solution();
        int[] nums = {0, 1, 2, 2, 4, 4, 1};
        Console.WriteLine(solution.MostFrequentEven(nums));
    }
}

The Python solution uses a dictionary to maintain the frequency of even integers. During the iteration of `nums`, frequencies are updated and checked to find the most frequent even number. In case of ties, it selects the smallest even number.

Complexity

Time Complexity: O(n), where n is the length of the input list.
Space Complexity: O(n), due to the storage of even numbers in the dictionary.

Try this approach in the editor

Approach 2: Sorting and Counting Consecutive Elements

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.

def most_frequent_even(nums):
    nums.sort()
    most_frequent = -1
    max_freq = 0
    curr_freq = 0

    for i in range(len(nums)):
        if nums[i] % 2 == 0:
            if i == 0 or nums[i] != nums[i - 1]:
                curr_freq = 1
            else:
                curr_freq += 1

            if curr_freq > max_freq or (curr_freq == max_freq and nums[i] < most_frequent):
                max_freq = curr_freq
                most_frequent = nums[i]

    return most_frequent

# Test case
print(most_frequent_even([0, 1, 2, 2, 4, 4, 1]))
import java.util.Arrays;

public class Solution {
    public int mostFrequentEven(int[] nums) {
        Arrays.sort(nums);
        int mostFrequent = -1, maxFreq = 0, currFreq = 0;

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] % 2 == 0) {
                if (i == 0 || nums[i] != nums[i - 1]) {
                    currFreq = 1;
                } else {
                    currFreq++;
                }

                if (currFreq > maxFreq || (currFreq == maxFreq && nums[i] < mostFrequent)) {
                    maxFreq = currFreq;
                    mostFrequent = nums[i];
                }
            }
        }
        return mostFrequent;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {0, 1, 2, 2, 4, 4, 1};
        System.out.println(solution.mostFrequentEven(nums));
    }
}
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int mostFrequentEven(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int mostFrequent = -1, maxFreq = 0, currFreq = 0;

    for (int i = 0; i < nums.size(); ++i) {
        if (nums[i] % 2 == 0) {
            if (i == 0 || nums[i] != nums[i - 1]) {
                currFreq = 1;
            } else {
                currFreq++;
            }

            if (currFreq > maxFreq || (currFreq == maxFreq && nums[i] < mostFrequent)) {
                maxFreq = currFreq;
                mostFrequent = nums[i];
            }
        }
    }

    return mostFrequent;
}

int main() {
    vector<int> nums = {0, 1, 2, 2, 4, 4, 1};
    cout << mostFrequentEven(nums) << endl;
    return 0;
}
function mostFrequentEven(nums) {
    nums.sort((a, b) => a - b);
    let mostFrequent = -1;
    let maxFreq = 0;
    let currFreq = 0;

    for (let i = 0; i < nums.length; i++) {
        if (nums[i] % 2 === 0) {
            if (i === 0 || nums[i] !== nums[i - 1]) {
                currFreq = 1;
            } else {
                currFreq++;
            }

            if (currFreq > maxFreq || (currFreq === maxFreq && nums[i] < mostFrequent)) {
                maxFreq = currFreq;
                mostFrequent = nums[i];
            }
        }
    }

    return mostFrequent;
}

console.log(mostFrequentEven([0, 1, 2, 2, 4, 4, 1]));
#include <stdio.h>
#include <stdlib.h>

int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int mostFrequentEven(int* nums, int numsSize) {
    qsort(nums, numsSize, sizeof(int), compare);
    int mostFrequent = -1, maxFreq = 0, currFreq = 0;

    for (int i = 0; i < numsSize; ++i) {
        if (nums[i] % 2 == 0) {
            if (i == 0 || nums[i] != nums[i - 1]) {
                currFreq = 1;
            } else {
                currFreq++;
            }

            if (currFreq > maxFreq || (currFreq == maxFreq && nums[i] < mostFrequent)) {
                maxFreq = currFreq;
                mostFrequent = nums[i];
            }
        }
    }

    return mostFrequent;
}

int main() {
    int nums[] = {0, 1, 2, 2, 4, 4, 1};
    int size = sizeof(nums) / sizeof(nums[0]);
    printf("%d\n", mostFrequentEven(nums, size));
    return 0;
}
using System;

public class Solution {
    public int MostFrequentEven(int[] nums) {
        Array.Sort(nums);
        int mostFrequent = -1, maxFreq = 0, currFreq = 0;

        for (int i = 0; i < nums.Length; i++) {
            if (nums[i] % 2 == 0) {
                if (i == 0 || nums[i] != nums[i - 1]) {
                    currFreq = 1;
                } else {
                    currFreq++;
                }

                if (currFreq > maxFreq || (currFreq == maxFreq && nums[i] < mostFrequent)) {
                    maxFreq = currFreq;
                    mostFrequent = nums[i];
                }
            }
        }

        return mostFrequent;
    }

    public static void Main() {
        Solution solution = new Solution();
        int[] nums = {0, 1, 2, 2, 4, 4, 1};
        Console.WriteLine(solution.MostFrequentEven(nums));
    }
}

This Python solution sorts the array and loops over it to count even numbers. The sorted arrangement simplifies tracking even numbers, updating the most frequent and smallest as needed.

Complexity

Time Complexity: O(n log n) given by sorting.
Space Complexity: O(n) for sorting, depending on the sort algorithm's implementation details.

Try this approach in the editor

Approach 3: Hash Table

We use a hash table cnt to count the occurrence of all even elements, and then find the even element with the highest occurrence and the smallest value.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array.

function mostFrequentEven(nums: number[]): number {
    const cnt: Map<number, number> = new Map();
    for (const x of nums) {
        if (x % 2 === 0) {
            cnt.set(x, (cnt.get(x) ?? 0) + 1);
        }
    }
    let ans = -1;
    let mx = 0;
    for (const [x, v] of cnt) {
        if (mx < v || (mx === v && ans > x)) {
            ans = x;
            mx = v;
        }
    }
    return ans;
}
func mostFrequentEven(nums []int) int {
	cnt := map[int]int{}
	for _, x := range nums {
		if x%2 == 0 {
			cnt[x]++
		}
	}
	ans, mx := -1, 0
	for x, v := range cnt {
		if mx < v || (mx == v && x < ans) {
			ans, mx = x, v
		}
	}
	return ans
}
use std::collections::HashMap;
impl Solution {
    pub fn most_frequent_even(nums: Vec<i32>) -> i32 {
        let mut cnt = HashMap::new();
        for &x in nums.iter() {
            if x % 2 == 0 {
                *cnt.entry(x).or_insert(0) += 1;
            }
        }
        let mut ans = -1;
        let mut mx = 0;
        for (&x, &v) in cnt.iter() {
            if mx < v || (mx == v && ans > x) {
                ans = x;
                mx = v;
            }
        }
        ans
    }
}
class Solution {
    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function mostFrequentEven($nums) {
        $max = $rs = -1;
        for ($i = 0; $i < count($nums); $i++) {
            if ($nums[$i] % 2 == 0) {
                $hashtable[$nums[$i]] += 1;
                if (
                    $hashtable[$nums[$i]] > $max ||
                    ($hashtable[$nums[$i]] == $max && $rs > $nums[$i])
                ) {
                    $max = $hashtable[$nums[$i]];
                    $rs = $nums[$i];
                }
            }
        }
        return $rs;
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Using HashMap to Count Frequencies

Time Complexity: O(n), where n is the length of the input list.
Space Complexity: O(n), due to the storage of even numbers in the dictionary.

Sorting and Counting Consecutive Elements

Time Complexity: O(n log n) given by sorting.
Space Complexity: O(n) for sorting, depending on the sort algorithm's implementation details.

Hash Table–

Complexity analysis

ApproachTimeSpaceWhen to Use
HashMap Frequency CountingO(n)O(k)General case when you want the fastest linear scan solution
Sorting + Consecutive CountingO(n log n)O(1) extra (depending on sort)When avoiding extra hash map memory or when the array is already sorted

Frequently asked questions

Is Most Frequent Even Element easy or hard?

Most Frequent Even Element is classified as an Easy problem on LeetCode. It mainly tests basic array traversal, conditional filtering for even numbers, and frequency counting with a hash map.

Most Frequent Even Element Python/Java solution

In Python, use a dictionary or collections.Counter to track counts of even numbers while scanning the array. In Java, use a HashMap<Integer, Integer> to store frequencies and update the answer based on maximum count and smallest value tie-breaking.

How to solve Most Frequent Even Element in O(n)?

Filter even numbers during a single pass and store their counts in a hash map. After updating the frequency for each number, track the maximum count and choose the smallest value when frequencies tie. Hash table insert and lookup operations keep the overall complexity at O(n).

What is the best approach for Most Frequent Even Element?

The best approach is HashMap frequency counting. Iterate through the array, track counts of only even numbers in a hash table, and keep the number with the highest frequency. This method runs in O(n) time with O(k) space where k is the number of distinct even values.

Is Most Frequent Even Element asked at Google/Amazon/Meta?

This problem reflects a common interview pattern involving frequency counting and hash maps. Variations of the problem appear in coding interviews at companies like Amazon and Google where candidates must identify the most frequent element under certain constraints.

What data structure is used in Most Frequent Even Element?

A hash table (HashMap or dictionary) is the primary data structure used in the optimal solution. It stores each even number as a key and its occurrence count as the value, enabling constant-time updates and lookups during traversal.

What is the time complexity of Most Frequent Even Element?

The optimal solution runs in O(n) time because the array is scanned once while updating frequencies in a hash map. An alternative sorting-based solution takes O(n log n) time due to the sorting step before counting consecutive elements.

Comments

Now write it yourselfClose this page and solve Most Frequent Even Element in the editor, without looking.
Practise Most Frequent Even Element