Skip to main content

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…

Let AA be a priority queue for maintaining a set of elements. Suppose AA is implemented using a max-heap data structure. The operation EXTRACT-MAX(A)\text{EXTRACT-MAX} (A) extracts and deletes the maximum element from AA. The operation INSERT⁡(A,key)\operatorname{INSERT}(A, key ) inserts a new element keykey in AA. The properties of a max-heap are preserved at the end of each of these operations.

When AA contains nn elements, which one of the following statements about the worst case running time of these two operations is TRUE?\text{TRUE}?

  1. A
    Both EXTRACT-MAX(A)\text{EXTRACT-MAX} (A) and INSERT⁡(A,key)\operatorname{INSERT}(A, k e y) run in O(1)O(1).
  2. B
    Both EXTRACT-MAX(A)\text{EXTRACT-MAX} (A) and INSERT⁡(A,key)\operatorname{INSERT}(A, k e y) run in O(log⁡(n))O(\log (n)).
    Correct answer
  3. C
    EXTRACT-MAX(A)\text{EXTRACT-MAX} (A) runs in O(1)O(1) whereas INSERT⁡(A,key)\operatorname{INSERT}(A, k e y) runs in O(n)O(n).
  4. D
    EXTRACT-MAX(A)\text{EXTRACT-MAX} (A) runs in O(1)O(1) whereas INSERT⁡(A,key)\operatorname{INSERT}(A, k e y) runs in O(log⁡(n))O(\log (n)).

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.