An unsorted array is given and we need to find top 5 elements in an efficient way and we cannot sort the list .
My solution :
-
Find the max element in the array. O(n)
-
Delete this max element after processing/using it.
-
Repeat step 1 & 2 , k times ( 5 times in this case ).
Time Complexity : O(kn) / O(n) , Space Complexity : O(1).
I think we can find the max element in O(logN) , So it can be improved to O(klogN). Please correct me if I am wrong.
Can we do better than this ? Using max-heap would be inefficient I guess?
PS – This is not any homework.
If you can use an auxiliary heap (a min heap with minus element at top) you can do that in
O(nlogm), wherenis the list length andmthe number of max elements to keep track of.Since the aux heap has a fixed max size (5) I think that operations on that structure can be considered
O(1). In that case the complexity isO(n).Pseudo code: