Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Values are pushed one by one into Python's heapq (a binary min-heap stored in a list), then one value is popped.

Problem: Values are pushed one by one into Python's heapq (a binary min-heap stored in a list), then one value is popped.
import heapq
h = []
for x in [7, 3, 9, 1, 5]:
    heapq.heappush(h, x)
snap = h[:]
print(snap, heapq.heappop(h), h)
What is printed?
  1. A. [1, 3, 9, 7, 5] 1 [3, 5, 9, 7]
  2. B. [1, 3, 5, 7, 9] 1 [3, 5, 7, 9]
  3. C. [7, 3, 9, 1, 5] 1 [3, 5, 9, 7]
  4. D. [1, 3, 9, 7, 5] 1 [3, 9, 7, 5]

Correct answer: A. [1, 3, 9, 7, 5] 1 [3, 5, 9, 7]

A heap is only partially ordered: children of index i sit at 2i + 1 and 2i + 2. Pushes sift up: [7] → [3, 7] → [3, 7, 9] → 1 rises past 7 and 3 → [1, 3, 9, 7] → 5 is placed under 3 → [1, 3, 9, 7, 5]. Pop moves the last element 5 to the root and sifts it down below 3 → [3, 5, 9, 7]. The list is not sorted; only h[0] is guaranteed minimal. Push/pop O(log n).

More Coding Interview Problems questions

Exams that ask this topic