Skip to content
Official PYQ · 2023

GATE CS 2023 Q36 — Binary Heaps

Explain with AI

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

Choose one option
View worked solution

Answer: B

A max-heap containing nn elements is represented as a nearly complete binary tree of height h=Θ(log⁡n)h = \Theta(\log n).

Let's analyze the worst-case time complexity of both operations:

  1. INSERT(A,key)\text{INSERT}(A, key):
    • To insert a new element, we place it at the next available leaf position (at the end of the array representation) to maintain the structural property of the complete binary tree.
    • We then perform a heapify-up (or bubble-up) operation to restore the max-heap property by comparing and swapping the element with its parent.
    • In the worst case, the newly inserted element travels from the leaf level to the root. The maximum number of swaps is proportional to the height of the tree, which is O(log⁡n)O(\log n).
  2. EXTRACT-MAX(A)\text{EXTRACT-MAX}(A):
    • The maximum element is always at the root of the max-heap, which can be accessed in O(1)O(1) time.
    • To delete this element, we replace the root with the last element of the heap and decrease the heap size by 1.
    • We then perform a heapify-down (or bubble-down) operation from the root to restore the max-heap property by swapping the element with its larger child.
    • In the worst case, this element travels from the root down to a leaf. The maximum number of swaps is proportional to the height of the tree, which is O(log⁡n)O(\log n).

Therefore, both EXTRACT-MAX(A)\text{EXTRACT-MAX}(A) and INSERT(A,key)\text{INSERT}(A, key) run in O(log⁡n)O(\log n) time in the worst case.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Binary Heaps questions