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