Most Frequent Even Element
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
Single even.
No even numbers.
4 appears 4 times.
Both appear 3 times, 2 is smaller.
2 and 4 both appear twice, 2 is smaller.
Algorithm Flow

Solution Approach
Count even elements. Track max frequency and smallest matching element. Return best or -1.
Time O(n), Space O(n).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
