IAE Academy

GATE 2023 CS Q.46: solution and answer

GATE 2023 · CSQ.46 · 2 marks · MCQ

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 TRUE?

  1. (A)

    Both and run in .

  2. (B)

    Both and run in .

  3. (C)

    runs in whereas runs in .

  4. (D)

    runs in whereas runs in .

See the question in the paper

Answer and solution

ANSWER

Option (B) is TRUE: both EXTRACT-MAX(A) and INSERT(A, key) run in O(log(n)) in the worst case.

Official answer: BSource: Official answer key, GATE 2023 CS (IIT Kanpur)

  1. A max-heap on elements is stored as a nearly complete binary tree of height , kept in an array.

  2. : place at the next free array position (a new leaf), then sift it up — repeatedly compare with its parent and swap while the max-heap property is violated. In the worst case the element travels from a leaf all the way to the root, giving comparisons and swaps.

  3. : the maximum sits at the root, so reading it is . To remove it while keeping the tree complete, the LAST element in the array is moved into the root position and the heap size is decremented.

  4. This relocated element is then sifted down (max-heapify): at each level it is compared with its larger child and swapped down if it violates the max-heap property, following a single root-to-leaf path.

  5. Sifting down takes comparisons and swaps in the worst case, since it can traverse the full height of the tree.

  6. So costs (locate the max) plus (restore the heap) overall — the same asymptotic order as .

  7. Hence both operations run in worst-case time, so statement (B) is TRUE.

KEY IDEA

A binary (max-)heap stored as a nearly complete binary tree has height ; both INSERT (sift-up from a new leaf) and EXTRACT-MAX (move last element to root, then sift-down/max-heapify) do work proportional to the tree's height, so both are in the worst case — reading the max itself is , but restoring the heap property after removing it is not.

WATCH OUT FOR

Assuming EXTRACT-MAX is overall because "the maximum is right at the root" (options C/D) — this only covers locating/reading the max. Removing it still requires refilling the root (with the last array element) and sifting it down through up to levels to restore the max-heap property, so the operation as a whole costs , not .

From the GATE 2023 CS paper. Every question of this paper · Download the full paper · All 26 Trees & heaps questions, with notes

More Trees & heaps questions