2

Is there a way to find the log n greatest elements in an array with n elements in O(n) time?

I would create an array based HeapPriorityQueue, because if all elements are available the heap can be created in O(n) time using bottom up heap construction. Then removing the first element of this priorityqueue should be in O(1) time isn`t?

amit
  • 166,614
  • 24
  • 210
  • 314
GameYoker
  • 55
  • 6

2 Answers2

4

Then removing the first element of this priority queue should be in O(1) time isn`t?

That will be O(logn), since you also remove the first element. Looking at it without removing is O(1). Repeating this removal logn times will be O(log^2(n)), which is still in O(n), so this solution will indeed meet the requirements.

Another option is to use selection algorithm to find the log(n)'th biggest element directly, which will be O(n) as well.

amit
  • 166,614
  • 24
  • 210
  • 314
  • I don't think repeating a removal is the only thing happening when trying to find the max elements. In the worst case (e.g. a presorted list in ascending order), won't you have to enqueue and dequeue `n` items (instead of `log(n)` times)? – StriplingWarrior Jun 17 '20 at 18:21
  • 2
    @StriplingWarrior I am not following, once you construct your heap (which is `O(n)` time to construct), each remove head operation is done in `O(logn)` (remove head, put instead bottom most right element, sift it down the heap until it's in place - at most O(logn) sifts) – amit Jun 17 '20 at 18:24
  • @amit thank you und thank you for the link to the selection algorithm! – GameYoker Jun 17 '20 at 18:28
  • 1
    You're right. Since inserting a value into a heap is `O(log(n))` I assumed that constructing the entire heap of `n` elements would be `O(n log(n))`, as it would be when constructing a sorted list. I found [this answer](https://stackoverflow.com/a/18742428/120955) which explains why constructing a heap would be `O(n)`. I still haven't fully wrapped my head around it, but I learned something new today. :-) – StriplingWarrior Jun 17 '20 at 18:40
1

Basically, yes. The creation of the heap takes O(n) and this dominates the algorithm.

Removing the first element may take either O(1) if the heap does not updates it's keys after removing or O(log n) if it does. Either way the complexity of removing log(n) elements from the heap with and without updating would be O(log n * log n) and O(log n) respectively. Both of which are sublinear.

Heladio Amaya
  • 886
  • 9
  • 16