Data Structures & AlgorithmsHardProduct Company SDE pattern

What is printed? (min-heap array after inserts)

What is printed? (min-heap array after inserts)
import heapq
h = []
for x in [9, 4, 7, 1, 8, 2]:
    heapq.heappush(h, x)
print(h, heapq.heappop(h), h)
  1. A. [1, 4, 2, 9, 8, 7] 1 [2, 4, 7, 9, 8]
  2. B. [1, 2, 4, 7, 8, 9] 1 [2, 4, 7, 8, 9]
  3. C. [2, 4, 7, 8, 9] 1 [2, 4, 7, 8, 9]
  4. D. [2, 4, 7, 9, 8] 1 [2, 4, 7, 9, 8]

Correct answer: D. [2, 4, 7, 9, 8] 1 [2, 4, 7, 9, 8]

After the six pushes the heap array is [1, 4, 2, 9, 8, 7] (a heap, not a sorted list). But print's arguments are all evaluated before anything is printed, and both h arguments are the same list object – heappop has already moved 7 to the root and sifted it below 2, so both show [2, 4, 7, 9, 8]. Push and pop are O(log n).

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic