Most Frequent Even Element

Most Frequent Even Element

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.

LeetCode Problem - 2404

class Solution {
    public int mostFrequentEven(int[] nums) {
        // Create a HashMap to store the frequency of even numbers
        Map<Integer, Integer> mp = new HashMap<>();

        // Iterate through the array to count the frequency of each even number
        for(int e : nums){
            if(e%2 == 0){ // Check if the number is even
                mp.put(e, mp.getOrDefault(e, 0)+1); // Increment the frequency of the even number in the map
            }
        }

        // If no even numbers are found, return -1
        if(mp.isEmpty()) return -1;

        // Initialize variables to track the most frequent even number and its frequency
        int flag = Integer.MIN_VALUE;
        int ans = 0, prevKey = 0;

        // Iterate through the keys (even numbers) in the map
        for(int e : mp.keySet()){
            // Get the frequency of the current even number
            int freqCurrent = mp.get(e);

            // If the frequency of the current even number is greater than the previous maximum frequency
            if(freqCurrent > flag){
                ans = e; // Update the most frequent even number
                flag = freqCurrent; // Update the maximum frequency
                prevKey = e; // Store the previous key
            }
            // If the frequency of the current even number is equal to the maximum frequency
            if (freqCurrent == flag){
                ans = Math.min(ans, Math.min(prevKey, e)); // Update the most frequent even number by choosing the smaller one
            }
        }
        // Return the most frequent even number
        return ans;
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!