Skip to content
Tech Interview Prep
Technical interview guide

Heaps / Priority Queues

A tree-shaped structure that keeps the min (or max) element accessible in O(1), with O(log n) insert and remove.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with library behaviour cited from CPython 3.14 heapq, the C++ standard containers, and java.util as of Java 21.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-5

How do min-heaps and max-heaps differ in their invariants, how do peek, push, and pop operate on each, and what are their exact time and space complexities?

Answer

A binary min-heap enforces parent(i) <= node(i) for every node except the root; a max-heap enforces parent(i) >= node(i). Both are complete binary trees stored in a contiguous array, so for zero-based indexing the left child of i is 2i + 1, the right child is 2i + 2, and the parent is floor((i - 1) / 2). The invariant is only local, it says nothing about the order of siblings or cousins, which is exactly why the extreme is cheap to read and everything else is not.

The three operations are structurally identical for both; only the comparator flips.

  • Peek: read index 0. O(1) time, O(1) space.
  • Push: append at index n, then sift up against the parent until the invariant holds. O(1) best case (the new key already satisfies the parent comparison), O(log n) worst case: one comparison per level on the leaf-to-root path.
  • Pop: move the last element to index 0, shrink by one, then sift down along the path of the extreme child (smaller child in a min-heap, larger in a max-heap). O(log n) time, O(1) auxiliary space.
OperationMin-heapMax-heapTimeAuxiliary space
Peekreturns minimumreturns maximumO(1)O(1)
Pushappend, sift upappend, sift upO(log n) worst, O(1) bestO(1)
Popremove root, sift downremove root, sift downO(log n)O(1)
Storagearray of n itemsarray of n items—O(n) total

When a heap is the wrong structure

The heap's advantage is a cheap extreme with cheap insertion. The moment you need anything else, a different structure wins:

  • Need both min and max, or arbitrary search/delete. A heap gives no ordering between siblings, so finding the max in a min-heap means scanning all leaves (indices floor(n/2) to n-1), O(n). A balanced BST (std::multiset, Java TreeMap) gives O(log n) peek, insert, delete, plus predecessor/successor and ordered iteration. Use it when you need more than the single extreme.
  • Data is static and you query repeatedly. A sorted array gives O(1) peek at either end and O(log n) binary search, at the cost of O(n) insertion. If you build once and read many times, sort instead of heapify.
  • Keys are small bounded integers. Counting sort or a bucket/radix structure gives O(1) amortized per operation, beating the heap's log n factor outright.
  • You need decrease-key. Dijkstra and Prim want it; a plain binary heap doesn't support it, so you either use an indexed heap or push duplicates and skip stale entries on pop (lazy deletion), which trades memory for simplicity.
  • You need stable FIFO tie-breaking. A heap is not stable; equal keys come out in arbitrary order. Add a sequence number to the key if order among ties matters.

A d-ary heap (say 4-ary) is a middle ground: a shallower tree speeds sift-down at the cost of more comparisons per level, and it often wins in practice on cache locality.

Standard library conventions

Python's heapq and Java's PriorityQueue are min-heaps; C++'s std::priority_queue defaults to a max-heap (std::less<T>).

Python
import heapq

min_h = [5, 1, 8]
heapq.heapify(min_h)          # [1, 5, 8]
peek_min = min_h[0]           # 1, O(1)
heapq.heappush(min_h, 3)      # O(log n)
extracted_min = heapq.heappop(min_h)   # 1, O(log n)

# Max-heap in Python: negate numeric keys
max_h = []
for x in [5, 1, 8]:
    heapq.heappush(max_h, -x)
peek_max = -max_h[0]          # 8, O(1)
extracted_max = -heapq.heappop(max_h)  # 8, O(log n)

Negation is a workaround, not a general solution: it only works for numeric keys and breaks for arbitrary objects unless you wrap them in a reversed-comparator class. If you need a real max-heap over custom types, supply that wrapper rather than negating.

A common failure mode is reaching for the opposite extreme from a heap you already have: retrieving the maximum from a min-heap, or vice versa. That is an O(n) leaf scan, not O(1), and it silently turns a log n algorithm into a linear one. Detect it by watching for a full scan inside a loop that was supposed to be heap-driven; the fix is a second heap or a balanced BST.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-1

Explain the heap invariant and how it changes a production decision.

Answer

The invariant. A binary heap is a complete binary tree stored in an array where, for a min-heap, every parent is ≤ both children: a[k] <= a[2k+1] and a[k] <= a[2k+2]. That is the whole contract. It says nothing about siblings, nothing about the left-to-right order of the array, and nothing about the array being sorted. The only position with a global guarantee is index 0: the minimum.

Python
import heapq
h = [5, 3, 8, 1]
heapq.heapify(h)
h        # [1, 3, 8, 5] - valid min-heap, not sorted
h[0]     # 1, the only guaranteed position

heapify is O(n), not O(n log n), because it sifts down from the last internal node and most nodes sit near the leaves. Push and pop are O(log n); peek is O(1).

The decision it changes. You are building a per-minute "slowest 100 requests" panel over ~10M requests. The invariant is what makes the bounded-heap pattern correct: keep a min-heap of size K, and the root is the weakest survivor. The exact element to evict when a bigger one arrives.

Python
def top_k(stream, k):
    h = []
    for x in stream:
        if len(h) < k:
            heapq.heappush(h, x)
        elif x > h[0]:
            heapq.heapreplace(h, x)   # evict smallest, keep K largest
    return sorted(h, reverse=True)

Trace top_k([5, 1, 9, 3, 7], 2):

xh beforeactionh after
5[]push[5]
1[5]push[1, 5]
9[1, 5]9 > 1, replace[5, 9]
3[5, 9]3 > 5? no, skip[5, 9]
7[5, 9]7 > 5, replace[7, 9]

Result [9, 7]. The heap holds the K largest but in heap order, not sorted order: the final sorted is required, and forgetting it is the classic bug.

Why not just sort. Sorting all 10M costs about n log n ≈ 10M × 23.3 ≈ 233M comparisons. The bounded heap costs about n log K ≈ 10M × 6.6 ≈ 66M: roughly 3.5× fewer, and O(K) memory instead of O(n). Comparisons are not the whole story, though: Python's sorted runs in C over a contiguous list, while the heap loop is Python-level per element. At K=100 the heap wins on memory and on streaming (you never hold the full minute), not necessarily on wall clock. Measure before claiming the win.

Criteria.

NeedHeapSorted array / bisectFull sort
Peek extremumO(1)O(1)O(1)
InsertO(log n)O(n) shift—
Full ordered iterationno, must drainyesyes
Arbitrary delete / decrease-keyno, lazyyes—
Streaming, bounded memoryyesyesno

When not to use one. If you need the full order, range queries, or decrease-key (Dijkstra, event schedulers with cancellation), a heap forces lazy deletion: mark the stale entry and skip it on pop, which grows the heap and leaks memory if cancellations outpace pops. If K is a large fraction of n, sorting is simpler and often faster. And if you need the k-th element once, quickselect is O(n) average with no heap at all.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

How would you reason about the array layout in a system you own?

Answer

The 90-second version

Array layout is a decision about the access pattern, not about the data. Before I change anything I answer three questions about the system I own: which loop is hot, what address stride does it generate, and how big is its working set against cache. Layout follows from those three. Picking AoS or SoA first is guessing.

So: profile, find the loop that dominates, and write down the address sequence it walks. Stride of one element: the layout is already right, look elsewhere. Stride of a whole record or a whole row: that is the thing to fix.

The three levers

  1. Interleaving: array-of-structs vs struct-of-arrays.
  2. Alignment and padding: field order inside the record.
  3. Index base and traversal order: zero- vs one-based, row- vs column-major.

Interleaving, with numbers. A 24-byte particle record {x,y,z,vx,vy,vz} (six floats) fits 2.67 records into a 64-byte cache line. A pass that reads only x (a bounding box, a centroid) gets 3 of the 16 floats the line delivered. Split into x[] y[] z[], the same pass uses all 16. About 5x fewer lines touched, and the prefetcher sees a unit stride instead of a 24-byte one.

LayoutFloats used per 64-byte line, x-only pass
AoS, 24-byte record3 of 16
SoA, separate arrays16 of 16

Padding. struct {char a; int b; char c;} is 12 bytes: a at 0, three bytes of padding, b at 4, c at 8, three more bytes of tail padding. Reorder to {int b; char a; char c;} and it is 8 bytes: a third smaller, so 8 records per 64-byte line instead of 5.

Traversal order. A 1000x1000 float matrix in row-major order is 4000 bytes per row. Walking it column-first strides 4000 bytes: 62.5 cache lines: per step, and since each line holds 16 floats, the pass re-fetches every line 16 times. Row-first fetches each line once. Same data, 16x the line traffic.

Fix the convention in one place.

C
// C11. Row-major, zero-based, derived in exactly one place.
static inline size_t idx(size_t r, size_t c) { return r * COLS + c; }
_Static_assert(sizeof(struct particle) == 24, "record size changed; re-check stride");

The static assert is the cheap half of the guard: it fails the build the day someone adds a field and silently changes the stride the hot loop depends on.

Failure modes I would actually look for

  • False sharing. Two threads writing count and sum in the same struct land in one cache line; the line ping-pongs between cores and every write costs a coherence miss. Detect with perf c2c; fix by padding each hot field to 64 bytes.
  • Mixed index conventions. Zero-based and one-based, or row- and column-major, both produce plausible-looking output. A spot check passes; only an invariant asserted over the whole array catches it.
  • Packed structs. __attribute__((packed)) removes the padding but makes every load unaligned. Fine on x86-64, a fault on some ARM configurations. Never pack the hot array.

When not to do this

SoA loses when you need whole records (serialization, a library call, random single-record access) because you now touch N arrays instead of one. AoS wins there, and wins outright when the working set fits in L1 (32-48 KB on current x86-64), where layout is noise and the right move is to stop. Column-major wins when the hot loop is column-wise, as in BLAS. The layout should match the loop, not the other way around.

The deciding criterion. If the working set is a few times L1, measure with perf stat -e cache-misses and move on. If it is 10x L2, layout is the whole game and the stride is the first thing I fix.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Walk through sift-up and sift-down, including where engineers most often get it wrong.

Answer

Assume a binary min-heap in a 0-indexed array: parent(i) = (i-1)//2, children 2i+1 and 2i+2. Each operation repairs one violated edge and walks a single root-to-leaf path.

Sift-up (insert). Append the new value at index n, then while i > 0 and a[i] < a[parent(i)], swap and set i = parent(i). One comparison per level, at most floor(log2 n) swaps. It stops when the parent is <= the element, or i reaches 0.

Sift-down (extract-min). The root is the answer; move a[n-1] to index 0, decrement the size, then while the node has children: pick the smaller child (compare a[2i+1] and a[2i+2] when the right child exists), and if that child < a[i], swap and descend; otherwise stop. Two comparisons per level (child-vs-child, then child-vs-element) so up to 2*floor(log2 n).

Trace. Start with [1,3,5,7,9,8,6]. Insert 2: append → [1,3,5,7,9,8,6,2]. i=7, parent 3 holds 7 > 2, swap → [1,3,5,2,9,8,6,7]. i=3, parent 1 holds 3 > 2, swap → [1,2,5,3,9,8,6,7]. i=1, parent 0 holds 1 <= 2, stop. Two swaps, three comparisons.

Extract-min: root 1 leaves, last element 7 moves to the root, size 7 → [7,2,5,3,9,8,6]. i=0, children 2 and 5, smaller is 2 at index 1; 2 < 7, swap → [2,7,5,3,9,8,6]. i=1, children 3 and 9, smaller is 3 at index 3; 3 < 7, swap → [2,3,5,7,9,8,6]. i=3, children at 7 and 8 are past size 7, stop. Two swaps.

Where engineers get it wrong.

  • Skipping the last-leaf move. Sift-down must start from the element that was at a[n-1], not from a child of the old root. Otherwise you leave a hole and read stale data.
  • Comparing against the wrong child. Sift-down must select the smaller child first; swapping with the left child when the right is smaller breaks the invariant silently. Sift-up compares against the parent, never a sibling.
  • Wrong stop condition. Sift-up stops on parent <= element, not only at the root; sift-down stops when the element <= both children, not only at a leaf. while i > 0 in sift-down or while i < n in sift-up is the bug.
  • Off-by-one on children: 2i+1/2i+2, and guard the right child with 2i+2 < n before reading it.
  • Direction mismatch: sift-down after insert or sift-up after extract leaves the heap locally ordered but globally wrong; it surfaces several operations later.

Detection: after every operation assert a[parent(i)] <= a[i] for all i > 0. That is O(n) per check, cheap in tests, and it catches all of the above.

Trade-offs. Sift-up costs one comparison per level, sift-down two, so insertion is the cheaper operation by a constant factor. That asymmetry decides build-heap: Floyd's method sifts down from the last internal node (n//2 - 1) to 0 for O(n) total, because most nodes sit near the bottom with tiny height; sifting each element up is O(n log n). For d-ary heaps, sift-up is O(log_d n) comparisons but sift-down must scan d children, O(d log_d n), so wider heaps favor insert-heavy workloads, and 4-ary heaps show up in schedulers for that reason. When decrease-key dominates (Dijkstra), a pairing or Fibonacci heap trades the array for O(1) amortized decrease-key.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

What does linear-time heapify guarantee, and what does it deliberately leave open?

Answer

Guarantee: heapify turns any array into a valid min-heap (or max-heap) in Θ(n) worst-case comparisons and swaps. The bound holds for every input, including adversarial ones: it is genuinely linear, not O(n log n) with a small constant.

What it leaves open: three things, and interviewers usually mean the first.

  1. The constant, and therefore wall-clock time. The bound is on comparisons, not seconds. Sift-down walks down the array with a stride that doubles each level, so it misses cache far more than a sequential scan does. At small n that can make the "linear" build slower than a "worse" asymptotic alternative. The linear bound says nothing about that.

  2. The arrangement. You get a heap, not the heap. Sibling order is unconstrained, equal keys have no defined relative order (heapify is not stable), and the array is not sorted. Two different inputs can produce the same heap; the same input can produce different heaps depending on which child you pick on a tie.

  3. The cost of what follows. Heapify optimizes construction only. Extraction is still O(log n) per element, so heapsort remains O(n log n) overall: the linear build does not change that.

Why it is linear. Sift-down from the last internal node to the root does work proportional to each node's height. In a complete tree of n nodes, the number of nodes at height h is ⌈n/2^(h+1)⌉, and each sift-down at height h costs at most 2h comparisons (two per level: pick the smaller child, compare with the parent). So total comparisons ≤ Σ_h 2h · (n/2^(h+1)) = 2n · Σ_{h≥0} h/2^(h+1) = 2n · 1 = 2n.

The sum Σ h/2^(h+1) = 1 is the whole trick: most nodes sit near the bottom where height is 0 or 1, so the expensive sift-downs are rare.

Contrast with repeated push. n pushes cost at most n·⌈log2 n⌉ comparisons.

nbuild-heap comparisons (≤)n pushes (≤)
10^32·10^3~10^4
10^62·10^6~2·10^7

At n = 10^6 that is roughly a 10x gap in comparisons, and it widens with n.

Failure modes.

  • Building by repeated insertion. Asymptotically worse, easy to write by accident, and it passes casual tests because the input distribution and scale that would expose it are exactly what a quick check leaves out.
  • Assuming heapify sorts. It does not; the array is a heap, not ordered. Binary search on it is wrong.
  • Assuming stability or a canonical result. If you need a deterministic arrangement, heapify will not give you one.

Use the library's heapify when the whole collection is available up front. If elements arrive incrementally you have no choice but repeated push, and then O(n log n) is the honest bound.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Derive heapsort from heap operations: build-heap then repeated extract-extreme, in place, with worst-case time and space complexity. Why do production systems prefer quicksort or mergesort despite heapsort's O(n log n) worst case: what does heapsort give up, and when would you still choose it?

Answer

Heapsort is two phases on one array. Build a max-heap in place: for i from n//2 - 1 down to 0, sift-down a[i]. That is O(n), because the nodes near the bottom are leaves or near-leaves and sift down at most a step or two. Then repeatedly extract the maximum: for end from n-1 down to 1, swap a[0] with a[end], then sift-down a[0] over the heap of size end. Each sift-down is O(log n), so the extraction phase is O(n log n) and dominates. The sorted region grows at the tail, so no second array is needed: auxiliary space is O(1).

python def heapsort(a): n = len(a) def sift_down(i, size): while True: l, r = 2i + 1, 2i + 2 largest = i if l < size and a[l] > a[largest]: largest = l if r < size and a[r] > a[largest]: largest = r if largest == i: break a[i], a[largest] = a[largest], a[i] i = largest for i in range(n//2 - 1, -1, -1): sift_down(i, n) for end in range(n-1, 0, -1): a[0], a[end] = a[end], a[0] sift_down(0, end)

Trace on [4, 1, 3, 2, 7]:

Build phase. i=1: a[1]=1, children a[3]=2 and a[4]=7, so swap with 7 -> [4, 7, 3, 2, 1]. i=0: a[0]=4, children a[1]=7 and a[2]=3, swap with 7 -> [7, 4, 3, 2, 1]; sift-down continues at index 1, where children a[3]=2 and a[4]=1 are both <= 4, so it stops. Heap is [7, 4, 3, 2, 1].

Extraction phase, each row showing the array after the swap and then after sift-down:

endafter swap a[0],a[end]after sift-down(0, end)
4[1, 4, 3, 2, 7][4, 2, 3, 1, 7]
3[1, 2, 3, 4, 7][3, 2, 1, 4, 7]
2[1, 2, 3, 4, 7][2, 1, 3, 4, 7]
1[1, 2, 3, 4, 7][1, 2, 3, 4, 7]

Sorted. Worst-case and average time are both O(n log n); auxiliary space is O(1). It is not stable: the swap of a[0] with a[end] moves equal keys across long distances.

Why production systems usually reach for quicksort or mergesort:

  • Quicksort: sequential partition scans give good cache locality and low constant factors, and it is in place. Worst case is O(n^2), which introsort removes by switching to heapsort once recursion depth exceeds about 2 log n, or by randomizing the pivot.
  • Mergesort: stable, O(n log n) worst case, but O(n) extra space and extra copying.
  • Heapsort: sift-down jumps between a parent and children that are far apart in memory, so it takes more cache misses per comparison than a partition scan, and it does more comparisons and swaps on average. It is also unstable.

Choose heapsort when you need a guaranteed O(n log n) worst case with O(1) auxiliary space: as the introsort fallback, in embedded or kernel code where an O(n) scratch buffer is not available, and in real-time paths where worst-case latency matters more than average throughput.

Failure modes: building a min-heap yields descending order; forgetting to shrink the heap size re-sorts the sorted tail; a wrong sift-down silently breaks the invariant. Detect them with adversarial inputs (already sorted, reverse sorted, all equal) and by asserting the heap property after each sift-down.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

How do you merge K sorted lists or streams using a min-heap, and what are the time and space complexity tradeoffs compared to pairwise merging?

Answer

To merge $K$ sorted streams with $N$ total elements, initialize a min-heap with the first element of each stream along with its stream identifier or iterator. Repeatedly extract the minimum element (the root of the heap), emit it to the output, and if the stream that yielded that element has a subsequent item, push that next item into the heap. Continue until the heap is empty.

Mechanically, the min-heap bounds auxiliary memory to at most $K$ active elements at any time. Sifting down a replacement element takes $O(\log K)$ time. Because every element out of $N$ enters and leaves the heap exactly once, the overall time complexity is $O(N \log K)$ and auxiliary working space is $O(K)$. When streaming from disk or network sockets, $O(K)$ working space avoids buffering all $N$ records in RAM.

Python
import heapq

def merge_k_sorted(streams):
    heap = []
    # Seed heap with (head_value, stream_index, iterator)
    for i, stream in enumerate(streams):
        it = iter(stream)
        try:
            heap.append((next(it), i, it))
        except StopIteration:
            pass
    heapq.heapify(heap)  # O(K)

    while heap:
        val, i, it = heap[0]
        yield val
        try:
            next_val = next(it)
            heapq.heapreplace(heap, (next_val, i, it))  # O(log K)
        except StopIteration:
            heapq.heappop(heap)                         # O(log K)

Tradeoffs versus Pairwise Merging

StrategyTotal TimeAuxiliary Space (In-Memory)Streaming-Friendly?Cache Behavior
Min-Heap ($K$-way)$O(N \log K)$$O(K)$Yes; needs 1 item per streamPointer/index chasing per sift-down
Naive Iterative Pairwise$O(N \cdot K)$$O(N)$ or $O(1)$ in-place listPoor; accumulates intermediate listsHigh sequential throughput per pass
Divide-and-Conquer Pairwise$O(N \log K)$$O(N)$ for buffers ($O(1)$ linked lists)Awkward; requires balanced passesExcellent spatial locality per merge pass
  1. Heap vs. Naive Pairwise: Merging list 1 into list 2, then into list 3, takes $\sum_{i=1}^K i \cdot (N/K) = O(N \cdot K)$ time. The heap reduces this by a factor of $K / \log K$.
  2. Heap vs. Divide-and-Conquer Pairwise: Pairwise tree reduction (merging pairs in $\lceil \log_2 K \rceil$ rounds) matches $O(N \log K)$ comparison complexity. On contiguous memory in RAM, divide-and-conquer pairwise often exhibits higher memory locality and branch predictability than navigating a heap array. However, for unbounded disk or network streams, pairwise merging requires materializing $\log K$ intermediate temp files or buffers, whereas the min-heap requires only $O(K)$ memory buffers simultaneously open.

Failure Modes & Gotchas

  • Payload Comparison on Ties: In Python, storing (val, it) causes heapq to compare iterator objects on duplicate values, throwing TypeError: '<' not supported between instances. A monotonic counter or stream index (val, stream_idx, it) breaks ties cleanly.
  • Heappop + Heappush vs. Heapreplace: Doing heappop() followed by heappush() does two sift operations ($2 \log K$ comparisons). Using heapreplace() executes a single sift-down pass, cutting heap constant factors in half.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

How does an indexed priority queue or standard min-heap optimize Dijkstra's shortest path algorithm, and what is the difference between lazy deletion and decrease-key?

Answer

The 90-second answer

Both structures run the same greedy loop: extract the unfinalized vertex with the smallest tentative distance, relax its edges, and both land near $O(E \log V)$. They differ in what happens when a relaxation finds a shorter path to a vertex already in the heap. An indexed priority queue keeps a vertex -> heap slot array, so it can decrease that vertex's key in place in $O(\log V)$; the heap never exceeds $V$ entries and auxiliary memory is $O(V)$. A standard binary heap (heapq, std::priority_queue) exposes no handle to an element, so the workaround is lazy deletion: push a second (dist, v) entry and discard the stale one when it surfaces. That costs $O(E)$ heap memory and $O(E \log V)$ time but needs no custom structure. On sparse graphs the two are within a constant factor; the indexed heap wins on memory and on dense graphs, lazy deletion wins on implementation cost.

Mechanics

Decrease-key (indexed min-heap). An auxiliary array maps vertex_id -> heap_index. Relaxing $(u,v)$ to a shorter distance: look up $v$'s slot in $O(1)$, overwrite its key, sift up in $O(\log V)$. Every swap moves both the heap entries and their two position-array entries. Heap size stays $\le V$: exactly $V$ pops ($O(V \log V)$) and at most $E$ decrease-keys ($O(E \log V)$), so $O((V+E)\log V)$ time and $O(V)$ memory.

Lazy deletion (standard heap). On a shorter path to $v$, push (dist[v], v) and leave the old entry in place. On pop, discard any entry whose distance exceeds the current dist[v] (equivalently, skip vertices already finalized). The heap can hold one entry per successful relaxation, so up to $E$ entries; each push/pop is $O(\log E) \le O(\log V)$, giving $O(E \log V)$ time and $O(E)$ memory.

Python
import heapq

def dijkstra_lazy(adj, source, n):
    dist = [float('inf')] * n
    dist[source] = 0.0
    pq = [(0.0, source)]
    while pq:
        d, u = heapq.heappop(pq)
        if d > dist[u]:      # stale duplicate, skip
            continue
        for v, w in adj.get(u, []):
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                heapq.heappush(pq, (dist[v], v))
    return dist

Trace on 0->1 (1), 0->2 (5), 1->2 (1), source 0:

popdist beforeaction
(0,0)[0,∞,∞]relax: dist[1]=1 push (1,1); dist[2]=5 push (5,2)
(1,1)[0,1,5]relax: 1+1=2<5 → dist[2]=2 push (2,2)
(2,2)[0,1,2]no outgoing edges
(5,2)[0,1,2]5 > dist[2]=2 → stale, discarded

Final dist = [0, 1, 2]. The heap held 4 entries for 3 vertices; (5,2) is the duplicate lazy deletion exists to absorb. With decrease-key the same run keeps at most 3 entries and rewrites (5,2) to (2,2) in place.

Comparison

PropertyIndexed PQ (decrease-key)Standard heap (lazy)
Heap size$\le V$up to $E$
Time$O((V+E)\log V)$$O(E \log V)$
Auxiliary memory$O(V)$$O(E)$
Implementationcustom heap + index mapoff-the-shelf heap

Failure modes

  • Dropping the stale check. Without if d > dist[u]: continue, finalized vertices get re-expanded once per stale entry, so the loop degrades toward $O(E \cdot \text{degree})$ work and can blow past the intended bound on dense graphs.
  • Corrupting the index map. In an indexed heap, if a sift swaps heap entries but not their position-array slots, decrease-key later edits the wrong vertex. The result is silently wrong distances, not a crash: test against brute-force Bellman-Ford on random graphs.
  • Dense graphs. At $E \approx V^2$, lazy deletion allocates $O(V^2)$ tuples; on millions of edges that is real GC pressure and cache misses versus the flat $O(V)$ arrays of an indexed heap.
  • Neither fixes negative edges. Both assume the extracted vertex is final; a negative edge breaks that invariant. Use Bellman-Ford ($O(VE)$) or Johnson's algorithm instead.

Alternatives. A Fibonacci heap gives $O(E + V \log V)$ amortized via $O(1)$ decrease-key, but its constant factors and complexity rarely beat a binary heap in practice. For dense graphs, the $O(V^2)$ array scan with no heap at all is often faster than either.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

How do you implement an efficient decrease-key operation in a binary min-heap, and why does standard Dijkstra's algorithm often prefer lazy deletion over an explicit decrease-key?

Answer

An explicit decrease-key on a standard binary heap requires $O(\log V)$ time, but locating the element in an array-backed heap takes $O(V)$ unless augmented with an auxiliary index mapping. Without augmentation, finding the key turns decrease-key into a linear search.

1. Implementing Decrease-Key via Auxiliary Indexing

To achieve $O(\log V)$ decrease-key in a binary min-heap, maintain a secondary mapping (such as a direct array pos[vertex_id] or hash map) that records the current index of each element inside the heap array.

Every time two nodes swap positions during sift_up or sift_down, their entries in pos must be updated synchronously.

Python
class IndexedMinHeap:
    def __init__(self):
        self.heap = []       # stores [key, val]
        self.pos = {}        # val -> heap_index

    def _swap(self, i: int, j: int):
        self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
        self.pos[self.heap[i][1]] = i
        self.pos[self.heap[j][1]] = j

    def _sift_up(self, idx: int):
        while idx > 0:
            parent = (idx - 1) >> 1
            if self.heap[idx][0] < self.heap[parent][0]:
                self._swap(idx, parent)
                idx = parent
            else:
                break

    def decrease_key(self, val, new_key: int):
        idx = self.pos[val]
        if new_key >= self.heap[idx][0]:
            return
        self.heap[idx][0] = new_key
        self._sift_up(idx)

2. Trade-offs: Explicit Decrease-Key vs. Lazy Deletion

Standard libraries like Python's heapq, C++ std::priority_queue, and Java's java.util.PriorityQueue do not expose an augmented position-tracking heap or an $O(\log V)$ decrease_key. Instead, practical graph implementations rely on lazy deletion (pushing duplicate (new_dist, v) pairs and discarding stale pops).

DimensionIndexed Heap (decrease-key)Lazy Heap (push duplicates)
Max Heap SizeExactly $V$ entriesUp to $E$ entries
Time Complexity$O((V + E) \log V)$$O((V + E) \log E) = O(E \log V)$
Space Complexity$O(V)$$O(E)$
Heap Operations$V$ pops, at most $E$ sift-upsAt most $E$ pushes, $E$ pops
Implementation OverheadCustom heap, 2-way sync pointers, hash/array lookups on swapsUses standard runtime heap primitives (heappush/heappop) directly

Why Dijkstra Prefers Lazy Deletion in Practice

  1. Constant Factors and Cache Locality: An indexed heap incurs indirection overhead on every swap. In practice, updating pos on every bubble-up step requires extra cache misses. By contrast, flat contiguous arrays in standard heaps boast tight loops.
  2. Graph Density: In sparse real-world graphs where $E = O(V)$ (e.g., road networks or web graphs where average degree is low), the heap size $E$ is within a small constant multiple of $V$. Because $\log E \le 2 \log V$, the asymptotic runtimes are virtually identical while the lazy implementation bypasses custom data structure maintenance.

Lazy deletion degrades when memory is tightly bounded or graphs are dense ($E \approx V^2$), where storing $O(E)$ elements in the heap risks out-of-memory errors and forces up to $V^2$ heap operations.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

How does lazy deletion change if the workload grows by two orders of magnitude?

Answer

The mechanism is unchanged at 100x: you mark and skip. What changes is which resource fails first. A lazily-deleted heap is bounded by the number of insertions, not the number of live entries, so 100x the work is a 100x heap unless the rebuild trigger is scale-invariant. Pop cost barely moves: log2(n) with n the insertion count goes from about 20 at 1e6 entries to about 27 at 1e8, roughly a third more comparisons per sift. Memory and rebuild cadence absorb the rest.

Give the threshold a ratio, not a clock. Let L be live entries and f the rebuild threshold expressed as stale/live. Rebuild when stale > f * L. The heap then holds N = (1+f) * L entries at its largest, whatever the work rate, and a rebuild fires once per f * L stale-generating events (a removal, or a superseding insert). Heapify of N entries costs fewer than 2N comparisons and fewer than N exchanges, so amortized rebuild cost per removal is 2N / (f * L) = 2(1+f)/f comparisons. At f = 0.5 that is 6 comparisons, against log2(1.5 * L) which is about 14 for one pop's sift when L = 10,000. The rebuild costs less than the pops it shortens.

The 100x arithmetic. At baseline, 10,000 stale events/s and f = 0.5, L = 10,000: a rebuild lands every 5,000 / 10,000 = 0.5 s. At 100x, 1,000,000 events/s: every 5 ms. Per-removal cost stays 6 comparisons; total rebuild work is 100x, per-operation work is flat, because the trigger is a ratio rather than a duration.

Now trigger on a 60 s timer instead, in a supersession-heavy workload where pops are rare. Stale entries pile up at the net insert-minus-pop rate. Baseline: 10,000/s * 60 s = 600,000 entries, roughly 70 MB with 8-byte int keys and tuples in a list, call it 120 bytes per entry. At 100x: 60,000,000 entries, about 7 GB, and the process dies on allocation before any algorithm misbehaves. Same bug, invisible at 1x, fatal at 100x. Hypothetical rates, real arithmetic.

Python
import heapq

class LazyMinHeap:
    def __init__(self, f=0.5):
        self.h = []        # (key, id)
        self.alive = {}    # id -> current key, live ids only
        self.stale = 0     # entries in h that are not live
        self.f = f

    def push(self, key, id_):
        if id_ in self.alive:       # supersede: old entry goes stale
            self.stale += 1
        heapq.heappush(self.h, (key, id_))
        self.alive[id_] = key

    def remove(self, id_):          # O(1)
        if id_ in self.alive:
            del self.alive[id_]
            self.stale += 1

    def pop(self):
        while self.h:
            key, id_ = heapq.heappop(self.h)
            if self.alive.get(id_) == key:
                del self.alive[id_]
                self._maybe_rebuild()
                return key, id_
            self.stale -= 1         # discarded tombstone
        raise IndexError("empty heap")

    def _maybe_rebuild(self):
        if self.stale > self.f * len(self.alive):
            self.h = [(k, i) for k, i in self.h
                      if self.alive.get(i) == k]
            heapq.heapify(self.h)
            self.stale = 0

Trace it: push(5,'a'), push(3,'b'), push(4,'a'). The second push of 'a' makes (5,'a') stale, so stale = 1 and alive = {'a': 4, 'b': 3}. pop() heappops (3,'b'), alive['b'] == 3, returns it, alive = {'a': 4}, stale = 1, and 1 > 0.5 * 1 so the rebuild drops (5,'a') and keeps (4,'a') with stale = 0. The next pop returns (4,'a'). The call after that finds h empty and raises IndexError rather than heappopping nothing.

Where it breaks at scale. First, no ratio trigger: heap length grows at the net insertion rate, and a stale entry whose key exceeds every live key never surfaces on its own, so it is pure resident memory. Watch heap_len / live_count and alert when it sits above 1+f for minutes. Second, the tombstone dict leaks: alive holds every id pushed and never popped, so at 100x with 1e6 new ids/s, a minute of unreaped tombstones is tens of millions of dict entries, gigabytes in CPython. Heap and dict have to be reclaimed together, which the rebuild above does. Third, the rebuild itself: 2N comparisons every 5 ms is nothing when N = 15,000, but if L is 5e6 you get a multi-millisecond stall on each rebuild and it shows in p99; amortize it by sifting incrementally or rebuild off the request thread.

When lazy deletion is the wrong tool. If removals are as frequent as inserts and memory is hard-capped, use an indexed binary heap: keep pos[id] beside the array, delete by swapping the target with the last element, sifting, and repairing both positions. Size is exactly the live set, removal is O(log n), and you pay an extra array plus pos fix-ups on every swap. Lazy deletion wins when cancellation is rare relative to pops and you want it in O(1); it loses when the live set is small next to churn, because the (1+f) factor then multiplies a number you cannot throttle.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Where does top-k versus sorting versus selection matter, and where is it irrelevant?

Answer

The choice matters in exactly one regime: large n with k small relative to n. Outside it the three methods are within a constant factor of each other, and comparison count is not what you should be optimizing.

They differ in what they guarantee, not only in speed:

MethodTimeSpaceOutput order
Full sortO(n log n)O(n)ordered
Size-k heapO(n log k)O(k)unordered
QuickselectO(n) expected, O(n²) worstO(1) extraunordered

A full sort is the only one that hands you the k elements ranked without a second pass. A size-k heap is the only one that runs on a stream you cannot hold in memory. Quickselect is fastest in expectation and has the weakest guarantee.

Where it matters: large n, small k. Take n = 1,000,000 and k = 10. A comparison sort does about n log₂ n ≈ 1,000,000 × 20 = 20 million comparisons. A size-k heap does about n log₂ k ≈ 1,000,000 × 3.3 ≈ 3.3 million in the worst case, and closer to n when few elements beat the current root. That is roughly a 6x gap in comparisons, and it widens as k shrinks. Quickselect beats both in expectation: one partition pass is n comparisons, and you stop as soon as the pivot lands at index n − k.

A trace makes the quickselect claim concrete. Find the 2 largest in [3, 1, 4, 1, 5, 9, 2, 6] with Lomuto partitioning and the last element as pivot:

  • pivot = 6; scan left to right, swapping every element < 6 toward the front: [3, 1, 4, 1, 5, 2, 9, 6], then swap the pivot into place → [3, 1, 4, 1, 5, 2, 6, 9].
  • The pivot lands at index 6, which is exactly n − k = 8 − 2. The top 2 are a[6] and a[7] = 6 and 9. One partition, 7 comparisons, done.

Where it is irrelevant.

  • Small n. At n = 1,000 the sort does ~10,000 comparisons and the heap ~3,000; both finish in microseconds and the library's constant factors dominate the asymptotics. Reach for the simplest correct call.
  • k close to n. The heap's edge is the log k factor; when k ≈ n, log k ≈ log n and the heap is a sort with more bookkeeping. Sort and slice.
  • Ordering is required. If the caller needs the k elements ranked, the heap and quickselect both leave an unordered set you must sort anyway: that second sort is O(k log k), which for large k erases the saving. Use heapq.nlargest, which returns them sorted, or sort directly.
  • The cost is elsewhere. If elements come off disk or the network, or the comparison is expensive but n is small, comparison count is a rounding error next to I/O. Profile before choosing.
  • The data already arrives ordered. A B-tree index, a sorted log, a merge of sorted runs: the ordering is free and selection is unnecessary.

The failure mode to avoid is treating "heap is O(n log k)" as an unconditional win. It wins only in the large-n, small-k, unordered-or-streaming case. Quickselect's expected O(n) hides a quadratic worst case that a crafted or adversarial input will find; if the input is untrusted, randomize the pivot or fall back to the heap, whose O(n log k) is a hard bound. And when k is a large fraction of n, the honest answer is "sort it": the asymptotics say so and so does the code you have to maintain.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Teach streaming medians to an engineer who has only seen it as a rule of thumb.

Answer

The core answer

Split the stream into a lower half and an upper half with two heaps. lo is a max-heap holding the smaller half, hi is a min-heap holding the larger half. Maintain the invariant len(lo) == len(hi) or len(lo) == len(hi) + 1. The median is then -lo[0] when the count is odd, and (-lo[0] + hi[0]) / 2 when even. Insert is O(log n): one push plus at most one rebalance move, each a heap op costing about log2(n) comparisons. Median is O(1). Memory is O(n): the two heaps together hold every element, so an unbounded stream grows without limit.

Python has no max-heap, so negate on the way in and out.

Python
import heapq

lo = []  # max-heap via negation: smaller half
hi = []  # min-heap: larger half

def add(v):
    heapq.heappush(lo, -v)
    heapq.heappush(hi, -heapq.heappop(lo))   # lo's largest -> hi
    if len(hi) > len(lo):                    # keep lo >= hi
        heapq.heappush(lo, -heapq.heappop(hi))

def median():
    if len(lo) > len(hi):
        return -lo[0]
    return (-lo[0] + hi[0]) / 2

Trace on 5, 2, 8, 1, 0 (values shown, not the negated heap contents):

addlohimedian
5[5][]5
2[2][5]3.5
8[2, 5][8]5
1[1, 2][5, 8]3.5
0[0, 1, 2][5, 8]2

Failure modes

  • Skipping the rebalance. Sizes drift, the root stops being the median, and the error is invisible on monotone input. Assert abs(len(lo) - len(hi)) <= 1 after every add in tests.
  • Sliding window with lazy deletion. If you mark expired elements instead of removing them, stale values sit at the roots and median() returns them. Pop roots while their timestamp is out of window before reading.
  • Overflow in fixed-width languages. (a + b) / 2 overflows for large 64-bit values; use a + (b - a) / 2 or widen to 128-bit.
  • Unbounded memory. Two heaps never forget, so a long-lived stream leaks. Cap it or switch structure.

Alternatives, and when two heaps are wrong

  • Sorted list with bisect.insort. O(n) insert (memmove), O(1) median. Simpler, and fine up to roughly 10^4–10^5 elements; past that the memmove dominates.
  • Order-statistic tree, skip list, or a Fenwick tree over coordinate-compressed values. O(log n) insert and median, and it supports deletion: the right pick for a sliding-window median where lazy deletion is too fiddly.
  • P² algorithm (Jain & Chlamtac, 1985). O(1) time and O(1) memory using five markers, but it returns an approximate median and is biased for small n. Use it when memory is the binding constraint and a few percent error is acceptable.
  • t-digest or Greenwald–Khanna. ε-approximate quantiles with bounded memory, mergeable across shards; GK uses O((1/ε) log(εn)) space. Pick these when you need arbitrary quantiles, not just the median, or when shards must be combined.

Two heaps are the wrong choice when you need deletion without lazy-deletion complexity, when memory is capped and approximation is acceptable, or when the question is a quantile other than the median. Otherwise they are exact, O(log n) per insert, and about twenty lines of code.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

A teammate proposes a design that hinges on the top-k pattern. How do you evaluate it?

Answer

First 90 seconds. Ask what top-k is buying before judging the heap. Four things decide it: is the answer required to be exact; are n and k bounded, and what are they; is the input append-only or does it need deletes and updates; and what is the per-event latency and memory budget. If the teammate can't answer the exactness question, that's the finding: everything else is downstream of it.

Then the mechanism, because the evaluation depends on it. A min-heap of size k keeps the current best k with the weakest at the root, so each arriving element is compared against the root and either dropped or swapped in. The root is the eviction point; that's the whole trick.

Python
import heapq

def top_k(stream, k):
    h = []
    for v in stream:
        if len(h) < k:
            heapq.heappush(h, v)
        elif v > h[0]:
            heapq.heapreplace(h, v)   # pop root, push v, one sift-down
    return sorted(h, reverse=True)

Trace on [3, 1, 4, 1, 5, 9, 2, 6], k=3:

vh[0]actionheap after
3–push[3]
1–push[1,3]
4–push[1,3,4]
111 > 1 false, drop[1,3,4]
51replace[3,5,4]
93replace[4,5,9]
242 > 4 false, drop[4,5,9]
64replace[5,6,9]

sorted(..., reverse=True) → [9, 6, 5]. Correct.

Cost: n heap operations of log2 k sift steps each. At n = 10^8 events/day and k = 100, that's 10^8 × ~7 steps ≈ 7×10^8 steps; at ~50 ns per step, roughly 35 s single-threaded per full pass, and 800 bytes of heap. A full sort of the same stream is 10^8 × 26.6 ≈ 2.7×10^9 comparisons, ~130 s at the same per-comparison cost, and 800 MB resident for int64. Illustrative figures, but they're the shape of the argument: the heap wins on memory by six orders of magnitude and on time by ~4×, and it wins because k is small, not because heaps are fast.

Where it stops winning: once k approaches n, log k approaches log n and you've paid heap overhead for nothing. Quickselect is O(n) average with O(n) memory, and a plain sort is simpler. Rule of thumb: heap when k is small relative to n (k under ~n/100) and the data arrives as a stream.

Alternatives to put on the table:

  • Exact, batch, k large: quickselect or sort.
  • Approximate, n huge: Misra-Gries with k−1 counters reports counts within n/k of true; count-min sketch plus a heap gives heavy hitters with error εN at width ⌈e/ε⌉ and depth ⌈ln(1/δ)⌉. Count-min only overestimates, so a threshold is safe but the ranking can be wrong.
  • Pre-aggregation: if the same top-k is queried repeatedly, maintain it incrementally rather than recomputing.

Failure modes to check for, each with a detection:

  • Max-heap inversion: keeps the k smallest. Detect with the trace above as a unit test.
  • k unbounded from user input: k = n degrades to O(n log n) with heap overhead. Cap k and fall back to sort.
  • Deletes or a sliding window: a heap can't remove an arbitrary element. You need lazy invalidation (keep counts, pop stale roots) or a different structure. Ask whether the window slides; if it does, the design as proposed is wrong.
  • Ties: if the consumer needs a stable order, the heap gives none. Run the same input twice and compare.
  • Skew: one hot key dominating means the top-k is correct and useless. Compare the k-th value's count to the first.

Go/no-go: go if exactness is required, k is bounded and small, the stream is append-only, and the latency budget absorbs ~7 comparisons per event. No-go if k is unbounded, if deletes matter, or if approximate answers are acceptable at a scale where a sketch is cheaper.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-14

When would you refuse a design because of stability and ties?

Answer

Refuse when the order of equal-priority items is observable and the structure doesn't guarantee it. That is the whole decision. Three conditions have to hold at once:

  1. Ties are not interchangeable: the output, an audit log, a replay, or a fairness guarantee depends on which equal item goes first.
  2. The structure you picked doesn't preserve insertion order among equals. Binary heaps (Python's heapq, Java's PriorityQueue) don't. A stable sort, a LinkedHashMap, or an insertion-ordered list does.
  3. No explicit tiebreaker is in the comparison key.

If any one is false, don't refuse. If all three hold, refuse and ask for the tiebreaker.

Why heaps aren't stable. A binary heap maintains only the parent ≤ children invariant. It never records arrival order, and heappush/heappop sift elements around on comparisons alone. Two equal keys are indistinguishable to the heap, so whichever ends up nearer the root pops first.

Python's heapq compares tuples element-wise. Push (priority, task) and equal priorities force a comparison of task, if tasks aren't orderable you get TypeError: '<' not supported between instances of 'Task' and 'Task'. So the tiebreaker isn't only about fairness; it's often required to make the code run at all.

Trace. Python 3, heapq, three equal-priority items pushed in arrival order c, a, b:

Python
import heapq
h = []
for name in ("c", "a", "b"):
    heapq.heappush(h, (1, name))
print([heapq.heappop(h) for _ in range(3)])

heappush appends then sifts up; heappop returns the root and sifts the last element down. The pops come out (1, 'a'), (1, 'b'), (1, 'c'): ordered by the second tuple element, not by arrival. Arrival order was c, a, b; the heap never saw it.

The fix. Add a monotonic counter as the second element so the key is total:

Python
import heapq, itertools
counter = itertools.count()
h = []
for name in ("c", "a", "b"):
    heapq.heappush(h, (1, next(counter), name))
print([heapq.heappop(h)[2] for _ in range(3)])   # ['c', 'a', 'b']

Equal priorities now pop in arrival order, and tasks are never compared.

Alternatives, and when to take them.

  • Ties genuinely interchangeable (idempotent, independent jobs): accept unspecified order, document it, don't pay for the counter.
  • Need a full stable ordering: sort the batch with a stable sort (sorted in Python is stable) instead of a heap. O(n log n) once, no per-push counter.
  • Need FIFO by construction: an insertion-ordered structure, or one queue per priority level.

Failure modes and detection. The symptom is a test that passes alone and fails in a suite, or a replay that produces a different order than the original run. Detection: assert pop order in a test that pushes equal keys out of order; log the tiebreaker value; run the same input twice and diff the output order. If the design can't state which equal item goes first, that is the refusal.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

How would you explain comparing non-comparable payloads without using the usual slogan?

Answer

The situation. You're using heapq as a priority queue and pushing (priority, payload) tuples. heapq is a min-heap over tuples, and tuple comparison is lexicographic: it compares element 0, and only if those are equal does it move to element 1. So the payload gets compared exactly when two entries share a priority.

What actually happens. Push two dict payloads at the same priority:

Python
import heapq
pq = []
heapq.heappush(pq, (1, {"id": "a"}))
heapq.heappush(pq, (1, {"id": "b"}))

Trace the second call. heappush appends the new item, giving [(1, {"id": "a"}), (1, {"id": "b"})], then sifts it up. The sift compares the new item against its parent: (1, {"id": "b"}) < (1, {"id": "a"}). The 1 == 1, so Python compares {"id": "b"} < {"id": "a"} and raises TypeError: '<' not supported between instances of 'dict' and 'dict'.

The first push never compares anything: the heap held one element. That's the whole trap: the code is correct until two priorities collide, so it passes any test whose priorities are distinct.

The fix that removes the comparison. Put a unique, monotonic value between priority and payload:

Python
import heapq, itertools
pq = []
seq = itertools.count()
heapq.heappush(pq, (1, next(seq), {"id": "a"}))
heapq.heappush(pq, (1, next(seq), {"id": "b"}))
# heap: [(1, 0, {'id': 'a'}), (1, 1, {'id': 'b'})]

A priority tie is now broken by seq, which is unique, so the comparison never reaches the payload. A side effect worth knowing: with a monotonic counter, equal-priority items pop in insertion order (FIFO), which is usually the behaviour you want anyway.

Alternatives, and when each is right.

ApproachCostWhen it's the right call
(priority, seq, payload)one int per entrydefault; payload is opaque or large
Wrapper class with __lt__ comparing only priorityPython-level __lt__ call per comparisonyou want heap entries as objects, or comparison logic is non-trivial
functools.cmp_to_keyPython-level comparison, sloweryou already have a cmp function; awkward with heapq since you must wrap each element
Serialise payload (json.dumps)O(payload size) per comparisonalmost never: makes comparison total but slow and order-dependent on dict key order

Don't use id(payload) as the tiebreaker: it's unique but unordered and can be reused after the object is garbage-collected, so pop order becomes non-deterministic.

Failure modes and how to catch them.

  • Crash: TypeError on the first priority tie. Detect with a property test that draws priorities from a tiny domain (random.randrange(3)) so ties are constant, and pushes payloads that aren't comparable.
  • Silent wrong order: if payloads are comparable (strings, ints), no error. The heap just orders ties by payload. That's a correctness bug, not a crash, and it's invisible unless you assert pop order.
  • Wrapper class whose __lt__ forgets to break ties: same crash, one level down.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-16

What failure would you inject to check a team's understanding of d-ary heaps?

Answer

Inject a sift-down that still uses the binary child formula. In a 4-ary heap the children of i are 4*i+1 .. 4*i+4; leave 2*i+1, 2*i+2 in place and the heap silently stops being a heap.

Python
# 4-ary heap, 0-indexed: children of i are 4*i+1 .. 4*i+4
def sift_down(a, i, n):
    while True:
        smallest = i
        left, right = 2*i + 1, 2*i + 2   # injected defect: binary child formula
        if left < n and a[left] < a[smallest]:
            smallest = left
        if right < n and a[right] < a[smallest]:
            smallest = right
        if smallest == i:
            return
        a[i], a[smallest] = a[smallest], a[i]
        i = smallest

Trace it on a = [1, 9, 8, 2, 5], a valid 4-ary heap (children of 0 are 9, 8, 2, 5, all ≥ 1).

  • extract_min: swap a[0] and a[4] → [5, 9, 8, 2, 1], n = 4, sift_down(0, 4).
  • i = 0: left = 1 (9), right = 2 (8). a[0] = 5 is smaller than both, so smallest = 0 and it returns.
  • Heap is now [5, 9, 8, 2]. Index 3 is a child of the root and holds 2, which is less than 5. The property is broken.
  • The next extract_min returns 5. The correct answer is 2.

The defect only fires once n ≥ d+1, because only then does the root have a child at index 3 or 4 that the binary formula never inspects. A hand-written smoke test on four elements passes every time.

Detection is a property test, not an example test: push 1000 random ints, pop them all, assert the output is non-decreasing. With d = 4 this fails within the first few pops. Pair it with an invariant check after every operation (for i in 1..n-1, a[(i-1)//d] <= a[i]) which localises the break to the operation that caused it instead of the pop that noticed it.

A second injectable, for teams using decrease-key: keep a pos[v] map from vertex to heap index, and have sift_up swap array entries without updating pos. A later decrease_key(v) then sifts from a stale index and moves the wrong vertex. Detect it with assert pos[a[i]] == i after every operation. This one is worth injecting separately because the first defect corrupts ordering while this one corrupts identity, and a team that only tests sorted output will miss it.

Operational cost is the reason to pick these over a crash: nothing throws. Dijkstra returns a distance that is too large, so a route planner emits a suboptimal route; a scheduler pops the wrong task. The bug is in the answer, not in the control flow, so it survives every test that only checks the code ran.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How should on-call treat an alert that names fibonacci heaps in theory and practice as the cause?

Answer

Treat the named cause as a hypothesis, not a fact. An alert that names a data structure as its cause is almost always mislabeled: heaps do not page you, saturated resources do. Your job in the first two minutes is to find the signal the alert was built on, decide whether it is real, and mitigate, not to adjudicate whether Fibonacci heaps are practical.

First 60–120 seconds. Acknowledge the page. Read the metric, not the label: which series fired, against what threshold, at what time. If the alert carries no metric, only the phrase "fibonacci heaps in theory and practice", treat it as a symptom-level page with a bad title and go to the service's own dashboards. Check the four things that actually cause latency pages: CPU saturation, GC or heap pressure, thread- or connection-pool exhaustion, and downstream latency. The heap type is a design decision made months ago; it does not change at 03:00.

Why the label is untrustworthy. A Fibonacci heap is a library or algorithm choice. Real implementations exist: Boost.Heap ships fibonacci_heap; Java's PriorityQueue and Python's heapq are binary heaps, but none of them emit an alert. If the service runs a graph algorithm on a Fibonacci heap, the alert is a proxy for "the algorithm is slow", and the heap is one input to that, not the cause. The phrase "in theory and practice" is the tell: whoever wrote the alert was reasoning about the algorithm, not the running system.

Alert labelWhat it can actually meanSignal to check
"fibonacci heaps"the graph workload got slowerp99 of the graph endpoint, CPU
"in theory and practice"template auto-filled from a design docthe alert rule's source and last edit
no metric attachedthe rule was written by hand, never validatedwhether the rule has ever fired before

Failure modes. The concrete failure is misdirection: you spend the incident reading about decrease-key while the real saturation (a connection pool pinned at its ceiling, say) keeps the service degraded. Detection is the fired metric diverging from the label: latency up, CPU flat, pool full. The second failure is alert fatigue. A page whose stated cause is a theory debate trains the team to ignore it, and the next real page gets ignored too.

Worked example (hypothetical figures). Alert fires: graph_query_latency_p99 > 500ms, cause: fibonacci heaps. On-call opens the dashboard: p99 went 40 ms → 180 ms at 03:12, CPU flat at 30%, connection pool at 20/20. The heap did not change; the pool saturated. Mitigation: raise the pool limit or shed load. The heap is a follow-up ticket, not the incident.

After the incident. Fix the alert: name the metric and the threshold, drop the causal claim. If the graph algorithm genuinely is the bottleneck, the alert should say "graph_query p99 above SLO" and link the design doc: the heap choice belongs in that doc, not in the page that wakes someone up.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-23

How does peek, pop, and the empty case interact with rollback, and where do people ignore that?

Answer

Core (first 60–120 seconds). Peek reads without mutating, so it never needs rollback. Pop mutates, so rollback means putting the item back, and that is only a state restore if nothing else touched the queue in between. The empty case is where rollback code misfires: there is nothing to put back, and a naive except wrapped around the pop pushes a sentinel instead of a real item.

Mechanism. On a binary heap, peek is heap[0], O(1); pop is heappop, O(log n); rollback is heappush of the same key, O(log n). The heap invariant comes back, but the state does not: equal keys reorder, and a concurrent consumer may already have taken the item. So pop-then-rollback is at-least-once, not exactly-once. Peek has none of this problem because it never removed anything.

The bug the empty case creates.

Python
import heapq

def process(q):
    item = None
    try:
        item = heapq.heappop(q)   # raises IndexError when q is empty
        handle(item)
    except Exception:
        heapq.heappush(q, item)   # "rollback"
        raise

Trace with q = []:

  1. item = None.
  2. heapq.heappop([]) raises IndexError.
  3. except Exception catches it: IndexError is an Exception.
  4. heapq.heappush(q, None) runs, so q == [None].
  5. raise re-raises IndexError to the caller.

The caller sees a clean IndexError, but the queue now holds a phantom None. The next call pops None, handle(None) fails on the first attribute access, that failure is caught by the same except, and None is pushed back: a self-sustaining loop. The fix is to separate the empty check from the rollback path: check if not q: return before the try, or catch IndexError distinctly from handle's exceptions.

Alternatives that make pop soft. Lease-based queues avoid re-push entirely. SQS ReceiveMessage hands you a message with a visibility timeout; only DeleteMessage commits it, and if you fail you skip the delete and the message reappears after the timeout. Kafka commits offsets: no commit means redelivery on rebalance. RabbitMQ with manual ack requeues unacked messages when the channel closes. All three trade rollback cost for duplicate delivery, so handlers must be idempotent. The other option is peek-then-commit: peek, do the work, pop only on success. That is atomic only if a lock covers both steps; otherwise it is a TOCTOU race where another consumer pops the item between your peek and your pop.

Failure modes to name. Phantom sentinel injected by the empty-case rollback path (above). Double processing when a rolled-back item is re-pushed and a second consumer also handles it. Reordering of equal keys after re-push, which breaks FIFO assumptions layered on top of the heap. Silent None/null propagation in Java (PriorityQueue.poll() returns null on empty, remove() throws) and undefined behaviour in C++ (std::priority_queue::pop() on empty), where the empty case does not even raise something you can catch.

When not to roll back by re-push. If you need exactly-once, a re-push cannot give it: use a lease with idempotent handlers, or a lock around peek-and-pop. Re-push is fine when duplicates are harmless and ordering among equal keys does not matter.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

What belongs in a runbook section on bounded heaps and backpressure, and what does not?

Answer

A runbook section on bounded heaps and backpressure carries the numbers and the actions; the reasoning lives in the design doc. What belongs: the capacity constant and where it is set, the drop policy in one sentence, the metric names with alert thresholds, the memory cost per unit of capacity, the backpressure signal the service emits when the bound is hit, and the exact step when the alert fires. What does not: what a binary heap is, why the product chose that drop policy, tuning history, client retry logic, or "monitor memory" with no metric attached.

The mechanism the section has to reflect: a min-heap's root is the lowest-priority item, so a bound is enforced by comparing the incoming priority against the root and either refusing the item or evicting the root. heapq.heapreplace pops the root and pushes the new entry in one O(log n) pass, so the heap size never exceeds capacity and the ordering guarantee holds over the retained items only: an evicted item is gone, not deferred.

Python
import heapq

CAPACITY = 50_000  # config: queue.max_entries

def offer(pq, entry, dropped):
    # entry = (priority, seq, payload); min-heap, root = lowest priority
    if len(pq) < CAPACITY:
        heapq.heappush(pq, entry)
        return True
    if entry[0] <= pq[0][0]:      # no more urgent than the worst retained
        dropped.inc()
        return False
    heapq.heapreplace(pq, entry)  # evict root, insert entry, size unchanged
    dropped.inc()
    return True

Trace it with the heap full at 50,000 and root priority 7. An entry with priority 3 hits 3 <= 7, increments dropped, returns False: the heap is untouched. An entry with priority 9 hits 9 > 7, heapreplace removes the priority-7 root, inserts the priority-9 entry, size stays 50,000, dropped increments. log2(50,000) ≈ 16 comparisons per eviction, sub-microsecond.

Memory arithmetic: a tuple of (int, int, ~120-byte payload) is roughly 240 bytes with interpreter overhead, so 50,000 entries ≈ 12 MB. Comfortable inside a 512 MB container. Unbounded at 20k entries/s across a 30-second overload is 600k entries ≈ 144 MB and still climbing, which is the OOM kill the bound prevents.

Belongs in the sectionDoes not
queue.max_entries = 50000 and the config pathWhat a heap is, or a heapq tutorial
Drop policy: evict lowest priority, refuse tiesWhy product chose that policy (link the ADR)
pq_size, pq_dropped_total; alert at pq_size > 45000 for 5m"Monitor memory" with no metric or threshold
Backpressure: 429 on ingest once pq_size hits capacityClient retry/backoff logic
Memory cost: ~240 B/entry, ~12 MB at capacityHistorical tuning ("we used 10k before")
Action: check upstream rate, then raise capacity or shed loadSpeculative future work

The failure mode is a section that names the mechanism but not the knob: the alert fires, the engineer greps for the constant, and the queue keeps growing while they read. Detection is the drop counter moving while pq_size sits pinned at capacity: that is the bound working, not a bug. What changes the decision: if the drop policy is a product call, the section links the ADR instead of restating it, and if capacity is per-tenant, it lists the per-tenant default rather than one global number.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

How would you review a pull request whose risk is priority inversion and starvation?

Answer

Clarify first: "priority" here means one of three things. OS thread priority (SCHED_FIFO/SCHED_RR), an in-process priority queue, or a request class in a scheduler. The review changes with each, so I'd ask which one the PR touches before reading the diff. Assumption I'd state out loud: the PR introduces or modifies a shared lock or a strict-priority queue on a path where high- and low-priority work contend.

Pass 1: priority inversion. Look for a lock a low-priority holder can block a high-priority waiter on. In the diff that is any mutex, synchronized block, ReentrantLock or std::mutex shared between the two paths. The question to settle in review: does that lock have priority inheritance or a priority ceiling? On POSIX it is explicit:

C
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT); /* or PTHREAD_PRIO_PROTECT */
pthread_mutex_init(&lock, &attr);

On Linux that becomes a PI futex. A plain std::mutex or a Java synchronized monitor does not do this, and Java's Thread.setPriority is a hint with no inheritance. If the PR leans on thread priority for correctness while the lock is a plain monitor, that is a blocking comment. The canonical cost of getting it wrong is Mars Pathfinder, July 1997: a low-priority meteorological task held a mutex, a medium-priority communications task preempted it, the high-priority ASI/MET task missed its deadline and the watchdog reset the spacecraft. The fix was enabling priority inheritance on that mutex, not adding CPU.

Pass 2: starvation. Look for a strict-priority queue with no ageing and no reserved share. Comment: what bounds the wait of the lowest class? If the answer is "high-priority traffic is bursty", ask for the number. Ageing makes it explicit:

Python
# example: 40 priority levels, one level gained per 100 ms of wait
effective = base_priority + min(39 - base_priority, (now - enqueued_at) / 0.1)

A base-0 item reaches the top in 3.9 s, so the worst-case wait for the lowest class is bounded at roughly 3.9 s regardless of arrival rate: a figure you can put in an SLO. The alternative is a reserved share (cgroup v2 cpu.weight, or a WFQ class with a guaranteed fraction), which bounds throughput rather than latency.

Tests to request. Two, both cheap. Inversion: a low-priority thread takes the lock, a medium-priority thread spins, a high-priority thread times lock acquisition; assert p99 under the deadline. Without PI this fails. Starvation: soak with sustained high-priority arrival and assert the oldest low-priority item's age stays under the bound. Queue depth alone will look healthy: that is the trap.

Failure modes. Ageing that is too aggressive collapses the ordering, so low-priority work starts beating high-priority; ageing that is too slow is starvation with extra steps. PI on a lock held across I/O just relocates the blocking. And a capacity increase fixes neither: both are properties of the ordering and the lock protocol, not of load.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

What trade-off does the oldest-item metric force that a junior answer usually skips?

Answer

The trade-off: oldest-item age buys starvation detection by giving up cheapness and early warning. It is a lagging, per-class, stateful metric, and it forces a threshold per class plus the acceptance that one stuck item holds it high forever.

Depth is one number, cheap, and it moves before the damage: backlog grows, then items age. Oldest-item age is the reverse: it is only non-zero after an item has already waited. So it is accurate about starvation and useless as a warning. That is the trade a junior answer skips. You are not picking the better metric; you are picking which failure you would rather be late on.

Three costs it forces:

  1. A threshold per class. One global number cannot work. Interactive traffic with a 200 ms p99 SLA and a batch class with a 30-minute SLA cannot share an alert line: any value either pages on batch or never fires on interactive.
  2. Per-class state and cardinality. You need an enqueue timestamp per entry, or a per-class FIFO head you can read in O(1). Emitting per class per queue is cheap (12 queues × 6 classes = 72 series); per class per queue per consumer-group per region is not.
  3. A poison item pins it. A single message parked at the head of a class makes oldest-age climb forever while throughput is fine. Depth never sees it; oldest-age sees nothing else.
deptholdest-item age
compute costO(1), one countertimestamp per entry, or per-class FIFO head
leading / laggingleadinglagging
fires on a poison itemnoyes, and never clears
thresholdone per queueone per class

Hypothetical arithmetic: interactive class, p99 SLA 200 ms, consumers drain 2,000 items/s, depth alert at 500 items → 500 / 2,000 = 250 ms of backlog, roughly at SLA. Now park one poison item at the head: depth is 1, oldest age is 40 minutes. Depth never fires; an oldest-age alert at 400 ms fires immediately and stays firing. The deciding criterion follows: if a class can hold a poison item, oldest-age must be paired with depth or a drain-rate condition, or you page forever.

Computing it forces a design choice too. Per-class FIFO sub-queues make oldest-age O(1): the head is the oldest:

Python
# per-class FIFO deque: append on enqueue, popleft on consume
oldest_age = {cls: now - q[cls][0].enqueued_at for cls in q if q[cls]}

That costs you global cross-class priority ordering. Keep one global priority heap and you keep the ordering, but per-class oldest-age becomes an O(n) scan per scrape, or needs a second index.

When not to reach for it: batch classes with 30-minute SLAs. A 400 ms threshold pages constantly, so set 45 min and accept the coarser signal. And if per-class cardinality is unaffordable, depth plus a drain-rate alert is the cheaper approximation, at the cost of missing starvation entirely.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

How would you brief product on why concurrent priority queues delays a ship date?

Answer

What I'd say in the room

"The priority queue is why we're slipping. Every worker that pulls the next job takes the same lock, so adding threads past about eight buys us nothing: we measured 61k jobs/s aggregate against 50k on a single thread, and p99 went from 0.4 ms to 24 ms. Two ways out: swap the data structure for one that doesn't serialise, or relax the ordering guarantee. The first is four days plus a load-test re-run; the second is one day but changes what 'next' means. I need you to tell me whether approximate ordering is acceptable, because that's a product call, not an engineering one."

That's the whole briefing. Product doesn't need the heap; they need the number, the options, and the decision that's theirs.

Why the queue is the bottleneck

A binary heap keeps the highest-priority element at index 0. poll() swaps the root with the last element and sifts the new root down, so every mutation touches the root: there's no way to partition that work across threads without changing the structure. java.util.concurrent.PriorityBlockingQueue wraps the heap in a single ReentrantLock held across the whole sift. Lock-free heaps exist in papers, but sift-down is a multi-step structural mutation rather than one CAS, so the practical alternatives are different structures, not a lock-free heap.

The arithmetic (hypothetical, from a load test I'd run before the meeting)

ThreadsAggregate throughputp99 poll latency
150k jobs/s0.4 ms
458k jobs/s1.8 ms
861k jobs/s9 ms
1659k jobs/s24 ms

Throughput flatlines at eight threads and p99 degrades 60×. That's the contention, and it's why "add more workers" isn't the fix.

Options and what each costs

OptionOrderingThroughputCost
Keep PriorityBlockingQueue, cap workers at 8exact61k jobs/s0 days, but SLA headroom is gone
ConcurrentSkipListMap as the queueexactscales with cores, higher per-op constant4 days + load test
Shard by priority bandapproximate within a bandscales with shard count1 day

What I'd ask product to decide

Whether jobs in the same priority band may be processed out of order. If yes, sharding ships this week and the delay disappears. If no, we take the four days. Sharding's failure mode is silent: it passes every functional test and only surfaces when two same-priority jobs have a dependency, so if we go that way I'd want the assumption written into the design doc and a metric on out-of-order completions.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

What is the smallest experiment that would change your mind about heaps versus balanced trees?

Answer

The experiment is a counter, not a benchmark: instrument the operation mix on one captured trace of the real workload.

Prior: default to the heap. It is a contiguous array with no pointers, and pop is a sift-down over ~log2(n) levels that mostly hit cache. The tree only earns its place if the workload needs something the heap invariant cannot give. So the smallest thing that would flip that prior is counting, not timing.

Take one representative trace: a captured request log, a replay of the batch job, whatever the production path actually is, and wrap the container with three counters:

  1. removals that are not the current extremum (delete-by-key, decrease-key, "cancel this job")
  2. consumers that iterate the structure in sorted order
  3. peak n the structure holds at once

Twenty lines around the container. No cluster, no load generator.

Falsification criterion. If counters 1 and 2 are zero across the trace, the tree is out: its extra capability is dead weight and you keep the heap. If counter 1 is nonzero, the heap forces the lazy-deletion workaround: mark the entry dead, leave it in the array, skip it on pop. That survives until dead entries dominate, at which point every pop pays to skip tombstones and memory grows without bound. One arbitrary removal per thousand operations is enough to make the tree the right call, because the heap's answer is a workaround with a growth bug, not a slower version of the same operation.

If semantics do not decide, the second experiment is the crossover. Both structures pop in O(log n), so the decision is constants and cache. At n = 1e6, log2(n) = 20 levels. The heap's 20 levels live in one contiguous array; the top few fit in L1/L2 and the rest stream. A red-black tree's 20 levels are 20 pointer dereferences, each a likely cache miss. Illustrative figures on a modern x86, hot cache, not measured here:

nheap poptree popnote
1e3~30 ns~60 nsnoise-dominated; pick on semantics
1e5~60 ns~150 nsheap ~2x
1e6~80 ns~250 nsheap ~3x

Measure at your actual n. Below n ≈ 1000 the gap is noise and the counter above is the only thing that should decide.

Mechanism, so the criterion is not a slogan. The heap invariant constrains only parent vs child. Siblings are unordered, so there is no path from the root to "the next smallest": ordered iteration means popping everything, O(n log n). A balanced tree stores the total order in its links, so in-order traversal is O(n) and a node's successor is O(log n). Arbitrary removal is the same story: a plain binary heap has no key→position map, so finding the element is O(n) and the sift is O(log n). An indexed heap, a binary heap plus a key→index map, does it in O(log n): look up the index, swap with the last element, sift. So the table's flat O(n) for heap removal holds only with no external handle. If your workload already carries a handle, that gap closes and the counter is the only thing left that decides.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

What would you ask a candidate who recites complexity summary but cannot apply it?

Answer

The question I'd ask

"Here's a stream of 10^8 events, each with a player id and a score. Keep the top 100 scores, and on every event tell me whether that player is already on the leaderboard. What structure do you use, and what does one event cost?"

That scenario forces the complexity summary to become a decision. It has a heap-shaped part (top-k) and a part a heap cannot do (membership), so a candidate who only memorised "push/pop O(log n)" has to notice the gap.

Assumptions I state before they answer: k is fixed at 100, scores arrive one at a time, no deletions, single thread. If they ask, memory is not the constraint.

What a strong answer does

Min-heap of size k for the top-k, plus a hash set of the ids currently in the heap. Per event: if the heap holds fewer than k entries, push and add to the set. Otherwise compare against the heap's min (peek, O(1)); if the score is larger, pop the min, remove that id from the set, push the new one, add its id.

Trace with k=2, scores 10, 20, 5, 30:

eventheapsetaction
10[10]{10}push
20[10,20]{10,20}push
5[10,20]{10,20}5 < min 10, reject
30[20,30]{20,30}evict 10, push 30

Cost: log2(100) ≈ 7 comparisons per push/pop, so ~7×10^8 comparisons over the stream; the set lookup is O(1) expected, ~10^8 hashes.

Probes

  1. "What if you only had the heap: what does the membership check cost?" The heap array is only partially ordered: parent ≤ children, but siblings are unordered. In [1,5,3,9,7], finding 7 means descending both branches, not one. Worst case O(k) per event, 100×10^8 = 10^10 comparisons: 100× the heap+set version. This probe separates the two mental models.

  2. "What breaks if you forget to remove the evicted id from the set?" Stale entries produce a false "already on the leaderboard". Detection: assert set size equals heap size after every event in tests, or reconcile periodically in production.

  3. "When would you drop the pair?" A balanced BST or sorted container gives O(log k) membership and insert without a second structure, at a higher constant and more allocation. For k in the hundreds the heap+set wins; if you also need rank or ordered iteration, the tree wins.

What I listen for

Whether they name the invariant that makes search linear, whether they price the sync between the two structures, and whether they reach for measurement only where the constant factor actually decides.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How would you document recognising a priority-queue problem so the next owner can operate it?

Answer

The doc is a card that lives next to the code, a module docstring or a RECOGNITION.md in the same directory, with four fields: shape, invariant, cost, symptom. A wiki page nobody opens mid-incident is not documentation.

Shape. The trigger is two questions asked of the loop, not of the data structure: does the body consume the extreme remaining element, and does the collection change between consumptions? Both yes → heap. One yes → probably not. Write the trigger as a sentence the next owner can grep for: "repeated extraction of the min/max from a set that mutates between extractions."

Invariant. A binary heap is a complete binary tree stored flat in an array: the children of index i are 2i+1 and 2i+2, and every parent compares ≤ its children (min-heap). That one property is why heap[0] is the minimum in O(1), and why push and pop cost O(log n): they repair a single root-to-leaf path, not the array. Building from an existing list with heapify is O(n), not O(n log n): it sifts down from the last parent, and most nodes sit near the leaves.

Cost.

NeedStructureExtract extremeInsertNote
Repeated extreme, mutating setbinary heapO(log n)O(log n)peek O(1); build O(n)
Fixed set, all items in ordersort onceO(1) after O(n log n)—re-sorting per iteration is O(n log n) each time
Membership onlyhash set—O(1) avgno ordering
Arbitrary delete + predecessorbalanced BSTO(log n)O(log n)ordered iteration, higher constants

Arithmetic worth putting in the doc: n = 100,000 items, k = 100,000 extractions. Heap: ~100,000 × 17 ≈ 1.7M comparisons. Sort inside the loop: ~100,000 × 100,000 × 17 ≈ 1.7 × 10^11. Milliseconds against tens of minutes on the same machine.

Worked trace: streaming top-k, the case where the set mutates while you consume it:

Python
import heapq

def top_k(stream, k):
    heap = []                       # min-heap holding the k largest seen so far
    for x in stream:
        if len(heap) < k:
            heapq.heappush(heap, x)
        elif x > heap[0]:           # beats the current k-th largest
            heapq.heapreplace(heap, x)
    return sorted(heap, reverse=True)

print(top_k([5, 1, 9, 3, 7, 2, 8], 3))

Trace, k=3: 5 → [5]; 1 → [1,5]; 9 → [1,5,9]; 3 beats root 1 → [3,5,9]; 7 beats 3 → [5,7,9]; 2 does not beat 5 → skipped; 8 beats 5 → [7,8,9]. Output [9, 8, 7]. Memory is O(k), time O(n log k): say that explicitly, because "top-k" invites the reader to assume O(n log n).

Symptoms, each with how to detect it:

  • Sort inside the loop: the profiler shows sorted/Arrays.sort on the hot path inside a loop frame, and doubling n multiplies wall time by ~4 instead of ~2. Detect it with a test that wraps the comparator and asserts the comparison count stays under n log n.
  • Wrong direction: a max-heap for top-k largest returns the k smallest. Caught by a test on a known 7-element input, not by a load test.
  • Lazy Dijkstra with no staleness check: the heap grows to O(E) entries instead of O(V); the symptom is heap size in logs exceeding the node count. Fix is if d > dist[u]: continue on pop.
  • Ties: heapq is not stable and compares tuples element-wise, so equal priorities with a non-comparable tiebreaker raise TypeError only when two keys collide. Fix: push (priority, seq, item) with a monotonic seq.

Leave the next owner a counterexample test: the same input through the heap version and a sort-in-loop version, asserting the heap version's comparison count. That test is the documentation: it fails the moment someone "simplifies" the heap away.

Curated: · Written: · Reviewed:

Difficulty: Medium