Heap / priority queue
A complete binary tree stored in a flat array where every parent is smaller (min-heap) or larger (max-heap) than its children, so the extreme element is always at index 0. It exists because many systems need to repeatedly take the next most urgent, earliest or best item from a changing set, and a heap does that in O(log n) with no pointers and excellent cache behaviour.
What it costs
| Operation | Cost | Note |
|---|---|---|
| Peek min / max | O(1) | Read index 0. |
| Insert (push) | O(log n) | Append at the end, then swap upward while smaller than the parent (sift up). |
| Pop min / max | O(log n) | Move the last element to index 0, then swap downward with the smaller child (sift down). |
| Build from n items | O(n) | Sift down from the middle backwards; faster than n inserts. |
| Top-k of a stream | O(n log k), k memory | Keep a min-heap of size k; push each item and pop if the heap exceeds k. |
Memory: Exactly n elements in a contiguous array, no pointers: 8 bytes per element for ids, or one small struct each.
An array that is secretly a tree
Index 0 is the earliest due time. Children of index i sit at 2i+1 and 2i+2. A push appends at the end and sifts up; a pop moves the last element to the root and sifts down. Only parent–child order is maintained.
How it works
- Elements live in an array. The children of the element at index i are at 2i+1 and 2i+2, and its parent is at (i−1)/2 rounded down. No pointers are stored; the arithmetic is the tree.
- The heap property says every parent is less than or equal to its children (for a min-heap). Nothing else is ordered: siblings can be in any order, so the array is not sorted, but index 0 is always the minimum.
- To push, append the new element at the end (the next free slot, which keeps the tree complete), then compare it with its parent and swap while it is smaller. It rises at most one level per swap, so at most log2(n) swaps.
- To pop, take index 0 as the result, move the last element into index 0, and compare it with its two children: swap with the smaller child while it is larger than either. It sinks at most log2(n) levels.
- For top-k over a stream of n items, keep a min-heap of at most k items whose root is the smallest of the current best k. For each new item, if it beats the root, replace the root and sift down. The heap always holds the k largest seen so far in O(log k) per item and O(k) memory.
Why it is shaped this way
- A complete tree in an array has no pointer overhead and touches adjacent memory on the way down, so it is fast on real hardware.
- Only the extreme is needed quickly; keeping the whole set sorted would cost O(n) per insert for no benefit.
Worked example
Scheduler in the notification system: 50M due times, deliver the earliest
- Marketing notifications deferred to the end of each user’s quiet hours create about 50M (due_at, notification_id) pairs per day. A min-heap keyed by due_at holds the pending set per worker shard: 5M entries per shard × 16 B = 80 MB, one contiguous array.
- The scheduler loop peeks index 0: if due_at ≤ now, pop it (log2(5M) ≈ 22 swaps, under a microsecond) and enqueue the delivery. Pushing a newly deferred notification costs the same 22 swaps. At 600 pushes and pops per second per shard the heap is idle almost all the time.
- Compare with scanning a table WHERE due_at ≤ now every second: 5M row scans per second, or an index range scan that still needs a transactional delete per row. The heap is the in-memory front, with the durable table behind it for restarts.
- Top-k referrers per link in the URL shortener analytics: a Count-Min sketch estimates each referrer’s count, and a min-heap of size 10 keeps the ten largest. Per click: one sketch update plus one heap compare, and only when the new count beats the current tenth place does a sift happen.
- Ranking in the news feed uses the same trick: score 500 candidate posts, keep the top 20 in a min-heap of 20 instead of sorting all 500.
When it is the wrong choice
- You need to find or update an arbitrary element, not just the extreme: a heap has no lookup by key, so pair it with a hash map (indexed heap) or use a balanced tree or skip list instead.
- Ordering must survive a restart or be shared across machines: the heap is an in-memory front; the durable, distributed version is a sorted set in Redis or a database index on the priority column.
- You need both the smallest and the largest, or ranges: use a balanced tree or skip list.
Interviewer follow-ups
Answer out loud before you open each one.
Why is a heap not a sorted array?
A sorted array makes insert O(n) because elements must shift. A heap maintains only the parent–child relation, so insert and remove-min are O(log n) swaps along one path. You give up the ability to read the second-smallest without popping the first, which most queues never need.
How do you find the top 10 of a billion items without sorting them?
Keep a min-heap of size 10. For each item, compare it with the root (the smallest of the current top 10); if it is larger, replace the root and sift down. That is one comparison per item for most items and O(log 10) for the rare ones that qualify, with 10 elements of memory.
How do you change the priority of an item already in the heap?
A plain heap cannot find it. Either keep a hash map from item to array index and update indexes on every swap (an indexed heap), then sift up or down from that position, or insert a new entry and mark the old one stale so it is skipped when popped. Schedulers often use the second trick because it is simpler.
When would you use a Redis sorted set instead of a heap?
When the queue must be shared by several processes or survive a crash. ZADD with the due time as score and ZRANGEBYSCORE for the earliest give the same operations in O(log n) over the network, backed by a skip list, at the cost of a round trip per operation.
Where it shows up
- Building blocks
- Keep urgent work ahead of bulk work · Rank instead of sorting by time · Run work later or on a schedule · Count big things with small memory · Measure p95 / p99, not the average · Drop load before you fall over
- Problems
- Notification System · News Feed (Twitter / X timeline) · URL Shortener (TinyURL / bit.ly)