Find the N-th most frequent number in the array

Luv picture Luv · Jun 10, 2012 · Viewed 9.5k times · Source
Find the nth most frequent number in array.
(There is no limit on the range of the numbers)

I think we can

(i) store the occurence of every element using maps in C++

(ii) build a Max-heap in linear time of the occurences(or frequence) of element and then extract upto the N-th element, Each extraction takes log(n) time to heapify.

(iii) we will get the frequency of the N-th most frequent number

(iv) then we can linear search through the hash to find the element having this frequency.

Time - O(NlogN) Space - O(N)

Is there any better method ?

Answer

Garima picture Garima · Aug 1, 2012

It can be done in linear time and space. Let T be the total number of elements in the input array from which we have to find the Nth most frequent number:

  1. Count and store the frequency of every number in T in a map. Let M be the total number of distinct elements in the array. So, the size of the map is M. -- O(T)
  2. Find Nth largest frequency in map using Selection algorithm. -- O(M)

Total time = O(T) + O(M) = O(T)