Write a mode method in Java to find the most frequently occurring element in an array

You should use a hashmap for such problems. it will take O(n) time to enter each element into the hashmap and o(1) to retrieve the element. In the given code, I am basically taking a global max and comparing it with the value received on ‘get’ from the hashmap, each time I am entering an element into it, have a look:

hashmap has two parts, one is the key, the second is the value when you do a get operation on the key, its value is returned.

public static int mode(int []array)
{
    HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
    int max  = 1;
    int temp = 0;

    for(int i = 0; i < array.length; i++) {

        if (hm.get(array[i]) != null) {

            int count = hm.get(array[i]);
            count++;
            hm.put(array[i], count);

            if(count > max) {
                max  = count;
                temp = array[i];
            }
        }

        else 
            hm.put(array[i],1);
    }
    return temp;
}

Leave a Comment