Pattern

Heaps and priority queues

Keep only the extreme elements you need on top, so repeated min/max or top-k queries stay logarithmic.

What it is

A heap is a tree-shaped structure that keeps the smallest (or largest) element accessible in O(1) and lets you insert or remove that extreme element in O(log n). It's the tool of choice whenever a problem needs "the current best/next/smallest" repeatedly, rather than a single sort at the end — a full sort costs O(n log n) up front and doesn't update well as new elements arrive, while a heap does both incrementally. Many heap problems actually run two heaps (a max-heap of smaller values and a min-heap of larger ones) or a heap paired with a hash map for tie-breaking or scheduling by count.

When it applies

Tells in the problem

The classic mistake

Reaching for a heap when the count k is a large fraction of n (say k ~ n), where maintaining a heap of size k costs about as much as just sorting and slicing — the heap only pays off when k is small relative to n. The subtler version of this mistake is picking the wrong heap direction: to find the k largest elements out of a stream, you want a min-heap of size k (so the smallest of your current top-k is the one you can cheaply compare against and evict), not a max-heap of everything, which forces you to keep every element you've seen. Interviewers notice when a candidate reaches for the max-heap-of-everything version and doesn't catch that it defeats the point of using a heap at all.

Questions to start with

All 12 heaps and priority queues questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.