Search code examples
algorithmfrequency

Find the N-th most frequent number in the array


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 ?


Solution

  • Your method is basically right. You would avoid final hash search if you mark each vertex of the constructed heap with the number it represents. Moreover, it is possible to constantly keep watch on the fifth element of the heap as you are building it, because at some point you can get to a situation where the outcome cannot change anymore and the rest of the computation can be dropped. But this would probably not make the algorithm faster in the general case, and maybe not even in special cases. So you answered your own question correctly.