Code Logo

Most Frequent Even Element

Published at24 Jul 2026
Easy 0 views
Like0

Given an integer array nums, return the most frequent even element. If there is a tie, return the smallest such element. If there is no even element, return -1.

This is a frequency counting DP problem. Iterate through the array, count occurrences of each even number using a hash map. Track the maximum frequency seen and the corresponding element. If a tie occurs, keep the smaller element.

The DP state is the frequency map of even numbers. As we iterate, we update the max frequency and best element. At the end, return the best even element or -1 if none found.

Edge cases include no even numbers (return -1), a single even number (return it), multiple occurrences of the same even number (return that number once), and ties where two even numbers have the same frequency (return the smaller one).

This frequency counting DP tracks the count of each even element and the current best candidate. The tie-breaking rule (pick smaller element) adds an extra condition to the standard max-frequency DP pattern.

This tracking pattern is a form of DP where each even number's count is the state, and the global best is updated incrementally. The tie-breaking rule adds an extra condition to the update step.

Example Input & Output

Example 1
Input
[2]
Output
2
Explanation

Single even.

Example 2
Input
[1,3,5,7]
Output
-1
Explanation

No even numbers.

Example 3
Input
[4,4,4,9,2,4]
Output
4
Explanation

4 appears 4 times.

Example 4
Input
[2,2,2,6,6,6]
Output
2
Explanation

Both appear 3 times, 2 is smaller.

Example 5
Input
[0,1,2,2,4,4,1]
Output
2
Explanation

2 and 4 both appear twice, 2 is smaller.

Algorithm Flow

Recommendation Algorithm Flow for Most Frequent Even Element
Recommendation Algorithm Flow for Most Frequent Even Element

Solution Approach

Count even elements. Track max frequency and smallest matching element. Return best or -1.

function solution(nums) {
  var freq = {};
  var best = -1, maxFreq = 0;
  for (var i = 0; i < nums.length; i++) {
    var n = nums[i];
    if (n % 2 !== 0) continue;
    freq[n] = (freq[n] || 0) + 1;
    if (freq[n] > maxFreq || (freq[n] === maxFreq && n < best)) {
      best = n;
      maxFreq = freq[n];
    }
  }
  return best;
}

Time O(n), Space O(n).

Best Answers

java
import java.util.*;
class Solution {
    public int solution(int[] nums) {
        Map<Integer,Integer> f=new HashMap<>();
        int b=-1,mf=0;
        for (int n:nums) {
            if (n%2!=0) continue;
            int cnt=f.getOrDefault(n,0)+1;
            f.put(n,cnt);
            if (cnt>mf||(cnt==mf&&n<b)) { b=n;mf=cnt; }
        }
        return b;
    }
}