Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python heapq code

Practice building a heap, adding priorities, removing the smallest item, and using a sequence tie-breaker.

Intermediate ~9 min read

Challenge 1

Rearrange the list in place into a valid min-heap.

python Your answer
import heapq

values = [8, 3, 6, 1, 5]

print(values[0])

Press Ctrl⌘Enter to check your answer

Challenge 2

Add a new priority to the existing min-heap while preserving its invariant.

python Your answer
import heapq

heap = [2, 5, 8]

print(heapq.heappop(heap))

Press Ctrl⌘Enter to check your answer

Challenge 3

Remove and store the smallest value from the heap.

python Your answer
import heapq

heap = [1, 4, 7]
next_priority = 
print(next_priority)
print(heap)

Press Ctrl⌘Enter to check your answer

Challenge 4

Push the task with priority 2 and a fresh tie-breaker sequence number.

python Your answer
import heapq
from itertools import count

pending = [(1, 0, "compile")]
sequence = count(1)

print(heapq.heappop(pending)[2])

Press Ctrl⌘Enter to check your answer