Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Practice · Coding

Heap (priority queue)

Keep the few elements that matter in a structure that hands you the smallest (or largest) in O(1) and updates in O(log n).


When it applies

3 5 8 9 7 12 smallest on top each parent ≤ its children; push and pop are O(log n)

Use a heap when you repeatedly need the current best of a changing collection: the smallest pending job, the largest profit you can afford, the k-th largest value seen so far. Sorting once does not help when elements keep arriving or leaving; a heap keeps the best at the top for O(log n) per insertion or removal.

Two shapes cover most problems. Keep k: a min-heap of size k holds the k largest items, and its top is the k-th largest, in O(n log k). Always take the best available: push everything that has become eligible, pop the best, repeat; this is the core of Dijkstra, Huffman coding and most scheduling problems.

Signals: "k-th largest", "top k", "merge k sorted", "cheapest", "schedule", "at most k picks", "stream". If you only ever need the minimum once, a single scan is enough; the heap earns its keep when the question is asked again and again.


The template

Write this from memory. Every problem in this section is a specialisation of it, and most bugs come from deviating without a reason.

import heapq

heap = []                              # heap[0] is always the smallest
for x in items:
    heapq.heappush(heap, x)            # O(log n)
    if len(heap) > k:
        heapq.heappop(heap)            # drop the smallest; the k largest remain
kth_largest = heap[0]

Problems

Or sit a timed interview: a fixed window, limited submissions, and a report at the end.