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 3, extract-min, insert 1, extract-min, insert 7, insert 3, insert 5, insert 5, extract-min, insert 6. What is the final array?
- A. [7, 5, 5, 6]
- B. [5, 6, 5, 7]
- C. [5, 5, 7, 6]
- D. [3, 5, 5, 6]
Correct answer: B. [5, 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.
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
- 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…
- 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…