Data Structures & AlgorithmsHardGATE 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 1, extract-min, insert 8, insert 5, insert 2, insert 8, insert 4, insert 4, insert 7, extract-min, insert 1. What is the final array?

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

Correct answer: D. [1, 7, 4, 8, 8, 5, 4]

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