Learning pathsPricingChecking sign-in…
Data structures

Heaps and top K

Maintain only the candidates you need.

Choose the retained candidates, priority extreme, and readiness rule before choosing a heap.

Mechanism and state

Selection keeps the best k candidates with the worst retained candidate at the root: a min-heap for kth largest, but reversed rank for frequent values or closest points. Merging sorted lists keeps one unconsumed head per source. Median maintenance splits all occurrences between a lower max-heap and upper min-heap. Smallest range keeps one representative per source and a running maximum. A cooldown scheduler separates eligible jobs from pending releases; an ineligible high-frequency job cannot run just because it has high priority. For weighted traversal, a heap entry is an immutable (cost snapshot, vertex) proposal. Keep tentative labels separately, insert a new proposal on a strict decrease, and discard a popped proposal whose cost no longer equals its label. A heap picture sorted for teaching is not the internal array or iterator order.

Why the pattern works

Top-k trimming preserves exactly the best min(k, processed) occurrences because only the new candidate can change membership. In a sorted-source frontier, every hidden successor is at least its visible head, so removing the minimum exposes the next global candidate. Median correctness needs both ordered halves and sizes differing by at most one. For covering ranges, the polled minimum remains a held representative while the other k-1 entries stay in the heap; advancing its source is the only way to raise that minimum. Scheduler optimality needs work and frequency-frame lower bounds plus a valid construction; heap usage alone is not a proof of minimum time. Nonnegative additive paths and minimax paths both have monotone extension: adding a nonnegative weight, or taking max with an edge jump, cannot lower a prefix cost. This lets a minimum current proposal finalize its vertex. The proof depends on the extension operator; merely using a heap proves nothing.

Work through an example

For [3,1,5,2,4], k=2, sorted display copies are [3], [1,3], [3,5], [3,5], [4,5]; the final root is 4. Before two arrivals, a kth-largest stream returns OptionalInt.empty. For median arrivals 5 then 1, routing 1 to the lower half temporarily makes sizes 2/0; moving its maximum 5 to the upper heap restores 1/1 and gives median 3. In a covering-range step, display the held minimum separately from the remaining heap so every source still has one representative. In DSA-113, 0→1 costs 9 while 0→2→1 costs 2. The cost-nine snapshot remains pending after a new cost-two snapshot is installed; later it is stale and skips all outgoing edges. In DSA-115 a label is the largest jump so far rather than a sum.

Where the reasoning fails

PriorityQueue iteration is not sorted order: figures show priority-sorted copies, not heap storage. Specify every tie rule and never subtract comparator operands. Full-int squared point distances can reach 2^63: use unsigned long comparison in Java and exact decimal strings in traces. Widen median addition, range subtraction, and cooldown arithmetic before evaluating them. Do not use sets where duplicate occurrences matter. Reusing merged nodes requires disjoint input ownership; empty median reads and incomplete kth streams need explicit APIs. Cooldown jumps should compress idle spans rather than allocate one cell per time unit. Never order entries by reading mutable labels from a comparator, finalize on enqueue, or subtract long costs in a narrowing comparator. A negative edge invalidates additive Dijkstra finality. Binary weights admit a deque with a stronger two-level ordering instead of a heap.

Reconstruct the reasoning

For each linked problem, name the root meaning, retained membership, tie rule, and state that is absent from the heap. Explain why median insertion may temporarily violate balance, why a held minimum still covers its source, and why a cooling job cannot compete with eligible jobs. Separate preprocessing, per-update, retained memory, output allocation, and displayed history costs; express constant-work k=1 updates with log(k+1). Explain why a stale snapshot is safe to discard and why each vertex has one valid pop. Compare the general heap of DSA-113, bottleneck extension in DSA-115, and exact front-to-back ordering of DSA-116.

Apply this foundation

Your study notes