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?
Asked
Active
Viewed 912 times
0

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 Answers
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.
H'.push(0, H[0])
count = ceil(log n)
while count > 0 do
(i, v) := H'.extract-max()
// takesO(log log n)
timeH'.push(2i+1, H[2i+1])
ifH[2i+1]
exists //O(log log n)
timeH'.push(2i+1, H[2i+2])
ifH[2i+2]
exists //O(log log n)
timecount := count - 1
- 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
-