A triage nurse, not a queue

Heaps & Priority Queues

The analogy

A normal queue serves whoever arrived first. A triage nurse ignores arrival order and always takes the most urgent patient next. A heap is that nurse: it does not keep everyone sorted, it only guarantees that the most urgent one is at the front, which is much cheaper than full sorting.

Visualizer

The heap as a tree

step 1 / 9
1327584

A min-heap drawn as a tree. It lives in a flat array — children of index i are at 2i+1 and 2i+2, so no pointers exist at all.array: [1, 3, 2, 7, 5, 8, 4]

import heapq

h = []
heapq.heappush(h, (2, "ship it"))
heapq.heappush(h, (1, "fix prod"))   # urgent
heapq.heappush(h, (3, "refactor"))

heapq.heappop(h)     # (1, "fix prod")
h[0]                 # peek — O(1)

# top-k without sorting everything: O(n log k)
heapq.nlargest(3, scores)

# max-heap: negate
heapq.heappush(h, (-priority, item))
Check yourself

Is the underlying array of a valid min-heap sorted?