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, insert 3, insert 2, insert 9, insert 3, insert 9, insert 6, extract-min. What is the final array?
- A. [6, 3, 3, 9, 4, 9]
- B. [3, 3, 6, 9, 4, 9]
- C. [3, 4, 3, 9, 6, 9]
- D. [2, 3, 6, 9, 3, 9]
Correct answer: C. [3, 4, 3, 9, 6, 9]
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.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- The array [19, 25, 3, 11, 7, 15, 4, 18, 13, 24, 23] (0-based indices) is turned into a binary min-heap by Floyd's method: for i from n/2 −…
- The array [16, 15, 9, 6, 4, 5, 1] (0-based indices) is turned into a binary min-heap by Floyd's method: for i from n/2 − 1 down to 0, sift…
- The array [7, 29, 10, 23, 27, 22, 21, 2, 16, 13] (0-based indices) is turned into a binary min-heap by Floyd's method: for i from n/2 − 1…
- The array [5, 11, 13, 2, 23, 26, 24, 18] (0-based indices) is turned into a binary min-heap by Floyd's method: for i from n/2 − 1 down to…
- The array [29, 16, 15, 27, 4, 6, 18, 25, 3, 8, 5, 7] (0-based indices) is turned into a binary min-heap by Floyd's method: for i from n/2…
- The array [12, 5, 1, 7, 4, 28, 20] (0-based indices) is turned into a binary min-heap by Floyd's method: for i from n/2 − 1 down to 0…