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 2, insert 4, insert 8, insert 2, insert 3, insert 8, insert 1, extract-min. What is the final array?
- A. [2, 3, 2, 4, 8, 8]
- B. [2, 2, 8, 4, 3, 8]
- C. [8, 2, 2, 4, 3, 8]
- D. [1, 4, 8, 2, 3, 8]
Correct answer: A. [2, 3, 2, 4, 8, 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
- Directed graph on vertices 0 to 7 with weighted edges (u→v (w)): 7→5 (4), 3→6 (8), 7→3 (9), 5→4 (3), 7→2 (10), 3→2 (2), 1→4 (12), 4→3 (3)…
- Directed graph on vertices 0 to 8 with weighted edges (u→v (w)): 8→7 (11), 0→1 (7), 5→8 (4), 5→1 (1), 4→1 (10), 8→5 (11), 7→8 (11), 3→5…
- Directed graph on vertices 0 to 5 with weighted edges (u→v (w)): 1→0 (8), 1→2 (1), 3→5 (5), 2→5 (6), 3→1 (1), 3→4 (9), 5→4 (7), 4→0 (11)…
- Directed graph on vertices 0 to 5 with weighted edges (u→v (w)): 0→2 (5), 4→1 (4), 5→2 (6), 2→0 (3), 0→5 (8), 4→3 (8), 1→2 (5), 3→0 (4)…
- Directed graph on vertices 0 to 6 with weighted edges (u→v (w)): 6→3 (12), 0→6 (12), 3→6 (3), 0→2 (4), 4→1 (1), 6→1 (6), 5→6 (6), 0→5 (3)…
- Directed graph on vertices 0 to 6 with weighted edges (u→v (w)): 4→6 (2), 5→2 (12), 0→2 (3), 4→2 (4), 5→1 (8), 5→3 (8), 6→5 (3), 3→6 (5)…