A priority queue is implemented as a max-heap. Initially, it has five…

2026

A priority queue is implemented as a max-heap. Initially, it has five elements. The level-order traversal of the heap is as follows: 20, 18, 15, 13, 12. Two new elements ‘10’ and ‘17’ are inserted into the heap in that order. What is the level-order traversal of the heap after the insertion of both elements?

  1. A.

    20, 18, 17, 15, 13, 12, 10

  2. B.

    20, 18, 17, 12, 13, 10, 15

  3. C.

    20, 18, 17, 10, 12, 13, 15

  4. D.

    20, 18, 17, 13, 12, 10, 15

Attempted by 8 students.

Show answer & explanation

Correct answer: D

In a max-heap stored via level-order array indexing, inserting a new value places it in the next open leaf position (the next array slot) and then sifts it upward: compare the new value with its parent at index ⌊(i−1)/2⌋, swap them if the child is larger, and repeat until the parent is larger or the root is reached. Each insertion is handled independently — a sift-up only ever moves the newly inserted value and never reorders siblings that are not on its path to the root.

Applying this to the given heap 20, 18, 15, 13, 12 (array indices 0 to 4):

  1. Insert 10 at index 5. Its parent sits at index ⌊(5−1)/2⌋ = 2, which holds 15. Since 10 < 15, the max-heap property already holds, so 10 stays at index 5 with no swap.

  2. Insert 17 at index 6. Its parent sits at index ⌊(6−1)/2⌋ = 2, which still holds 15. Since 17 > 15, swap them: 17 moves to index 2 and 15 moves to index 6.

  3. Re-check 17 at its new index 2 against its new parent at index ⌊(2−1)/2⌋ = 0, which holds 20. Since 17 < 20, the property holds and 17 stops climbing.

Cross-checking the final array [20, 18, 17, 13, 12, 10, 15]: the root 20 exceeds its children 18 and 17; 18 exceeds its children 13 and 12; and 17 exceeds its only child 15 (10 is a leaf) — every parent-child pair satisfies the max-heap property, confirming no further swaps are needed.

So the level-order traversal after inserting 10 then 17 is 20, 18, 17, 13, 12, 10, 15.

Explore the full course: Coding For Placement

Loading lesson…