Predict the output
What does this print?
import heapq
heap: list[int] = []
for v in [5, 3, 8, 1]:
heapq.heappush(heap, v)
before = list(heap)
print(before, heapq.heappop(heap), heap)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [1, 3, 8, 5] 1 [3, 5, 8]
Right: 1 climbs to the root; after the pop, 5 moves to the top and sinks below 3.
Only the root is guaranteed smallest; the rest of the list is in heap order, not sorted order.
Why not the others?
- B [1, 3, 5, 8] 1 [3, 5, 8]. A heap is not fully sorted; 5 sits below 3 at the end.
- C [1, 3, 8, 5] 1 [5, 3, 8]. After the pop, the new root sinks below the smaller child.
Steps come from running the Python solution.
Text version
Push 5, 3, 8, 1:
- Push 5: 0 swaps up, list [5].
- Push 3: 1 swap up, list [3, 5] (slots 1 → 0).
- Push 8: 0 swaps up, list [3, 5, 8].
- Push 1: 2 swaps up, list [1, 3, 8, 5] (slots 3 → 1 → 0).
Result: [1, 3, 8, 5]
Push 9, 7, 5, 3, 1:
- Push 9: 0 swaps up, list [9].
- Push 7: 1 swap up, list [7, 9] (slots 1 → 0).
- Push 5: 1 swap up, list [5, 9, 7] (slots 2 → 0).
- Push 3: 2 swaps up, list [3, 5, 7, 9] (slots 3 → 1 → 0).
- Push 1: 2 swaps up, list [1, 3, 7, 9, 5] (slots 4 → 1 → 0).
Result: [1, 3, 7, 9, 5]