Time complexity to get min elements from max-heap

后端 未结 6 2367
渐次进展
渐次进展 2020-12-28 18:46

I was asked in an interview:

What is the best time complexity in getting the min element(s) from a max-heap?

I replied as O(1) a

6条回答
  •  不思量自难忘°
    2020-12-28 19:36

    Best complexity is O(n). Sketch proof:

    • The minimum element could be absolutely any of the lowest-level nodes (in fact it could even not be at the lowest level, but let's start with these).
    • There could be up to n/2 lowest-level nodes.
    • All of them need to be examined, because the one you're looking for might be in the last place you look. Examining all-but-1 of them doesn't tell you whether the last one is the minimum or not.
    • Hence Omega(n) examinations required.

    The bound is tight, since clearly we can do it in O(n) by ignoring the fact that our array happens to be a heap.

    Moral: it's probably called a heap because (as with the heap of clothes on your bedroom floor) it's easy to get at the top and difficult to get at the rest.

提交回复
热议问题