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