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) assuming the heap size is known and the heap is implemented as a binary heap using an array. This way as per my assumption, the min value is at heap_array[heap_size]
.
My question is that if this answer is correct. If not, what is the correct answer?
We can check all the nodes in the min-heap to get the maximum element. Note that this approach works on any binary tree and does not makes use of any property of the min-heap. It has a time and space complexity of O(n).
The time complexity to find the minimum element in a min-heap is O(1) , that is the primary purpose of such a container. It was literally made to find the smallest (or largest) element in constant time. The operation that is O(logn) is insertion.
We must use a linear search to search all of the elements in order to find the smallest element and heap. It will take O(n) time to traverse all of the elements using linear search.
(CLRS 6.1-4) Where in a max-heap might the smallest element reside, assuming that all elements are distinct? Solution: Since the parent is greater or equal to its children, the smallest element must be a leaf node.
My question is that if this answer is correct.
No, that's not correct. The only guarantee you have, is that each node contains the maximum element of the subtree below it. In other words, the minimum element can be any leaf in the tree.
If not what is the correct answer?
The correct answer is O(n). In each step you need traverse both left and right sub-trees in order to search for the minimum element. In effect, this means that you need to traverse all elements to find the minimum.
Best complexity is O(n)
. Sketch proof:
n/2
lowest-level nodes.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With