Data Structures & AlgorithmsVery hardGATE CS · TCS NQT

Start with an empty binary min-heap stored in an array, where the children of index i are at 2i + 1 and 2i + 2. insert(x) appends x and swaps it upward while its parent is larger. extract-min saves the root, moves the last element to the root and sifts it down, swapping with the smaller child while that child is smaller than the element (on a tie between two children the left child is used). Apply in order: insert 4, extract-min, insert 5, insert 2, insert 9, insert 2, insert 6, insert 2, extract-min, insert 5, insert 7. What is the final array?

  1. A. [2, 5, 2, 9, 6, 5, 7]
  2. B. [2, 2, 9, 2, 6, 5, 7]
  3. C. [2, 2, 5, 5, 6, 9, 7]
  4. D. [9, 2, 2, 5, 6, 5, 7]

Correct answer: A. [2, 5, 2, 9, 6, 5, 7]

Sift-up and sift-down must both run; skipping the sift-down after extract-min, or skipping the sift-up on insert, leaves an array that is not a heap. Choosing the right child on a tie gives a different array with the same keys.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic