Let be a priority queue for maintaining a set of elements. Suppose is implemented using a max-heap data structure. The operation extracts and deletes the maximum element from . The operation inserts a new element in . The properties of a max-heap are preserved at the end of each of these operations.
When contains elements, which one of the following statements about the worst case running time of these two operations is
GATE CSE 2023Data Structures › Heaps & Priority QueuesVerified
GATE CSE 2023 PYQ: Let A A A be a priority queue for maintaining a set of elements. Suppose A A A is implemented using a…
- ABoth and run in .
- BBoth and run in .Correct answer
- Cruns in whereas runs in .
- Druns in whereas runs in .
Answer
(B) Both EXTRACT-MAX ( A ) \text{EXTRACT-MAX} (A) EXTRACT-MAX ( A ) and INSERT ( A , k e y ) \operatorname{INSERT}(A, k e y) INSERT ( A , k ey ) run in O ( log ( n ) ) O(\log (n)) O ( lo g ( n )) .
Approach
In a max-heap, the maximum is at the root. However, after deleting it, the heap property must be restored by moving the last element to the root and sifting it down, which costs O(log n) in the worst case. INSERT may also need to bubble a new key up to the root, also O(log n) in the worst case.
The maximum element can be accessed in O(1), but deleting it and restoring the heap requires O(log n) worst-case time. Insertion may also require O(log n) worst-case time to bubble up. Hence option B is correct.
Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.