0

The title says it all; What is the most efficient way to find the log nth maximum number in a max heap with n elements?
ps: The text book I'm reading vaguely explained a solution with time complexity of O(lognloglogn) by using another heap that I can't understand, can we do better than that?

Amen
  • 1,524
  • 5
  • 22
  • 41
  • An obvious, and not very interesting, solution is to simply do log n extract-max operations, resulting in running time `O((log n)^2)`. – blazs Mar 20 '17 at 08:36

1 Answers1

1

Let H be the original max-heap. Let H' be another max-heap, initially empty, that operates on pairs (index, value) of elements from the first heap and orders the pairs based on the second component.

  1. H'.push(0, H[0])
  2. count = ceil(log n)
  3. while count > 0 do
    1. (i, v) := H'.extract-max() // takes O(log log n) time
    2. H'.push(2i+1, H[2i+1]) if H[2i+1] exists // O(log log n) time
    3. H'.push(2i+1, H[2i+2]) if H[2i+2] exists // O(log log n) time
    4. count := count - 1
  4. return v

The reason we have O(log log n) bounds on running times of operations of H' is that H' contains at most log n elements and each operation runs in time logarithmic in the number of elements of the heap, which is O(log log n).

The total running time is obviously O(log n log log n). I'm assuming the original max-heap H is represented with an array.

blazs
  • 4,705
  • 24
  • 38
  • how do you extract the min from H in O(log logn) time? That heap contains n elements, – Amen Mar 20 '17 at 08:52
  • @Amen no need to extract min, you need to extract max. And `max` is, by the construction of the heap, at index 0 of the array representing the heap... – blazs Mar 20 '17 at 09:36
  • I'm sorry my comment was wrong, I meant to say you can't do line 4. of your code in that time complexity. – Amen Mar 20 '17 at 09:54
  • Well, I claim you can. `H'` contains _at most_ `log n` items where `n` is the number of items in `H` (note that `H` and `H'` are different max-heaps). Since `H'.extract-max()` runs in time `O(log (H'.size())` and `H'.size()=O(log n)`, we have that its running time is `O(log log n)`. – blazs Mar 20 '17 at 09:56
  • Aha, now I see it's been changed, initially you were extracting min from H. :) – Amen Mar 20 '17 at 09:58
  • Oh yes, that was a typo, sorry (but the description was correct). – blazs Mar 20 '17 at 09:58