Heap and Priority Queue: Priority queues and online top-k
Goal: Learn the pattern first, then apply it to the 7 roadmap problems in this chapter.
When this pattern appears
You repeatedly need the smallest/largest current candidate while the set changes.
The reusable idea
Choose min-heap or max-heap based on which item should be evicted or processed next.
A deliberate problem-solving routine
- Write the input and output in plain language. Identify whether order, duplicates, or mutation matter.
- Work a tiny example by hand; label the state you wish you had at each step.
- Choose the structure or invariant that stores that state.
- Establish a brute-force baseline, then show exactly which repeated work the pattern removes.
- State the invariant before the loop, after each iteration, and at termination.
- Test smallest, boundary, duplicate, and adversarial cases.
Watch the animated pattern
The diagram above this lesson animates the core state changes for this chapter. Use pause and step to predict what moves next. The same invariant should explain each application, even when the problem story changes.
Questions to ask yourself
What is the one candidate that must be processed next, and how do I keep it available?
Common failure modes
Heap root meaning, stale entries, initialization, ties, and output ordering.
Chapter problems from the workbook
- #66 · Kth Largest Element in a Stream — Day 38, Easy. Open problem ↗
- #67 · Last Stone Weight — Day 38, Easy. Open problem ↗
- #68 · K Closest Points to Origin — Day 39, Medium. Open problem ↗
- #69 · Kth Largest Element in an Array — Day 39, Medium. Open problem ↗
- #70 · Task Scheduler — Day 40, Medium. Open problem ↗
- #71 · Design Twitter — Day 40, Medium. Open problem ↗
- #72 · Find Median from Data Stream — Day 41, Hard. Open problem ↗
Interview explanation
A concise explanation has four parts: the key observation, the maintained invariant, why each step preserves it, and the time/space complexity. Avoid naming a pattern as a substitute for proving the step is safe.