Time complexity to get min elements from max-heap

后端 未结 6 2366
渐次进展
渐次进展 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:40

    Best complexity is O(n).

    Rather than, not wrote here a lot about that,
    The min element in MAX-heap, and the MAX element in min-heap
    Can be also at the (lowest level - 1) and not always in lowest level.

    explain:
    because in heap there is an option of missing nodes from the right side of the lowest level, it could be not a balancing (fully) tree, what makes it to have leafs also in (lower level -1).

    what means that there are n/2 to check. so in big O term it's equal to O(n).

    Examples for situation like that:

    • MAX-heap[10,9,1,8,7] (1 is the smaller value, but didnt apear in lowest level)
    • min-heap [8,10,20,17,15] (20 is the max value, but didnt apear in lowest level)

提交回复
热议问题