views:

476

answers:

3

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?

A: 

If you are using Linq you can do this

IEnumerable.Max();
Chris
My dear friends, I know this, please read my comment on Younes's answer. I can write myself one templated function that would find minimum and maximum integer from an array of int, float, or double, or long type.
Rajendra Kumar Uppal
+2  A: 

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.
Axarydax
@AxerydaxWhat if there are 10 million integers and ofcourse I don't want to use 10 million integer extra space?
Rajendra Kumar Uppal
@Rajendra, you may then like to use a hash table which uses a hash function to create keys, and not uses the array index as key.
Neeraj
@NeerajFine, agreed. What is your take on a situation like following?1. array of 10 million integers.2. only one duplicate (our answer)3. rest (10 million - 2) are distinct integers.
Rajendra Kumar Uppal
I have said that this works if you don't care about memory.
Axarydax
@Rajendra,you can take an array of size 2*10 million, use a hash function and hash the entries, avoid collision by linear probing or separate chaining and proceed in way as described.Also if the range of numbers in your array is small,you can further extend the method demonstrated by Axarydax by using `(element - min)` in place of `element`
Neeraj
A: 

You can use a hashtable with "the number in array" as key and "occurrences" as values.

Sample code be like this:

 hashtable h;
 for every entry in array
      search hashtable
           if present, increment num_occurrences
           else, create new entry

 Iterate over all the entries in hashtable and return one 
 with max num_occurrences

As searching in hash is considered O(1), the overall complexity will be O(n).

A special case of this problem is when the numbers in array are in a given range, in that case take another array of ints with size of maximum value in the original array,and use the index of new array as key and the number stored in this array as count of occurrences.

Return the index of the largest value in this array.

Neeraj