Find maximum occuring integer (Mode) in an unsorted array
arrays
Solution
I think you want to find out element that has most occurences in the array - if you don't care about memory, traverse the array once, increase count of each element in the hashtable. Then find the one with highest count. You'd need one traverse of array and one of the hashtable.
so in pseudocode:
hashtable hash;
foreach(element in array){
if(!hash.contains(element))
hash[element] = 1;
else
hash[element]++;
}
int max = 0;
max_element;
foreach(element in hash)
if(hash[element] > max)
{
max_element = element;
max = hash[element];
}
//max_element contains the maximum occuring one.
Problem
How to find the integer occurring maximum number of times (mode) in an unsorted array of integers? One `O(nlogn)` approach I could think of is to sort. Is there any other better approach?