Heaps & Priority Queues
Understand the heap as its own interview subject: how the structure works under the hood, how priority queue APIs expose it, and which classic problem shapes it unlocks. Interviewers lean on heaps because one simple invariant connects directly to complexity arguments, library fluency, and pattern recognition.
part ofData structures & algorithmsoverview, primer and where to startread it →on this pageshowhide
explore
- Heap Mechanics13 questions
- Heap Property & Array Representation5 questions
- Core Operations: Sift, Insert, Extract4 questions
- Building a Heap: Bottom-Up Heapify4 questions
- Priority Queue APIs8 questions
- The Priority Queue Abstraction4 questions
- Library Priority Queue Quirks4 questions
- Canonical Heap Patterns18 questions
- Top-K Selection4 questions
- K-Way Merge5 questions
- Two Heaps: Running Median5 questions
- Heap vs Sorting vs Quickselect4 questions
- Heap Variants: d-ary, Indexed, Fibonacci4 questions
- Computer Scienceskillanchors this topic
- Data Structures & Algorithmsskillanchors this topic
- AI & Data Scientistrole
- AI Engineerrole
- AI Red Teamingrole
- Android Developerrole
- Backend Developerrole
- Blockchain Developerrole
- Cyber Security Expertrole
- Data Analystrole
- Data Engineerrole
- DevOps / SRE Engineerrole
- DevSecOps Engineerrole
- Forward Deployed Engineerrole
- Frontend Developerrole
- Full Stack Developerrole
- Game Developerrole
- Java Backend Developerrole
- Java SDETrole
- Kotlin Backend Developerrole
- MLOps Engineerrole
- Machine Learning Engineerrole
- Network Engineerrole
- PostgreSQL DBArole
- QA Engineerrole
- Software Architectrole
- iOS Developerrole
questions
page 2 of 2In frequency top-50 over 10 million distinct terms, where does the memory actually go?
basics
~20 sAlmost all of it goes to the counting phase. Ranking terms by frequency needs a count for every one of the 10 million distinct terms held at once; the size-50 heap adds fifty entries. The heap bounds the output, not the memory.
Why does a two-heap running median report a far-too-low value if rebalancing only shrinks the max-heap?
basics
~20 sRepairing only the max-heap-too-large case lets the min-heap grow without limit whenever samples arrive above the current median, so the max-heap keeps an old small value on top and the reported median sinks toward it. Both repair directions are required.
How do you keep a two-heap median over a fixed trailing window when the expiring sample isn't at a top?
basics
~20 sHeaps remove only their top, so expiring samples are deleted lazily: mark the departing value as pending removal, track logical sizes separately from physical heap sizes, rebalance on the logical counts, and discard stale tops before reading the median.
Sort, size-k heap, or quickselect — which survives an unbounded stream of price updates?
basics
~20 sOnly the bounded candidate heap survives. It sees each record once and holds O(k) state, so an answer is available at any moment. Sorting and quickselect are offline: both need the entire input materialized with random access.
In an indexed heap's sift-down, the position map is updated for only one side of each swap. What breaks?
basics
~20 sThe sinking element's map entry goes stale, so a later reprioritization by identity resolves to the wrong array slot and mutates a different element's key. Nothing fails at the moment of the bug; the damage surfaces much later.
What does a size-k heap commit you to on a memory-capped gateway ingesting an unbounded sensor stream?
basics
~20 sA size-k heap commits you to one frozen question. Bounded state and a single pass let the job run under the cap, but every value that lost to the bar is destroyed, so a different k or metric means re-ingesting the stream.
Top-k becomes a user-tunable parameter up to the full catalog — which selection strategy do you commit to?
basics
~20 sCommit to one default with a documented, measured threshold rather than three tuned paths. As k approaches n, O(n log k) converges on O(n log n) and the candidate structure holds O(n) items — above the crossover, just sort.
Why can inserting into a priority queue keyed by (priority, sequence, payload) tuples fail outright?
basics
~20 sComposite keys compare component by component, so when priority and sequence both tie, the queue falls through to comparing payloads — and payload records with no defined ordering make that comparison fail. A strictly unique sequence number stops the fall-through.
Why is a heap's replace-top cheaper than an extract followed by an insert?
basics
~20 sReplace-top overwrites the root with the new key and runs a single sift-down. Extract-then-insert runs a sift-down to repair the removal and then a sift-up for the arrival — about twice the tree traversal, plus a needless shrink and regrow of the structure.
Why does an implicit array heap outperform a node-per-element pointer tree in a hot loop?
basics
~20 sSame asymptotics, much better constants. The implicit layout stores only keys, contiguously: no child or parent references, no per-node allocation, and navigation is arithmetic rather than a dependent memory load, so the hot top levels stay resident in cache.
How do you choose merge fan-in k when merging thousands of sorted streams under a memory ceiling?
basics
~20 sMemory bounds the fan-in, not comparison cost. Comparisons grow as log k, but every open source needs a resident read buffer, so memory grows linearly in k. Take the largest k whose per-source buffers still read efficiently.
When would you not keep an exact two-heap median for per-endpoint latency across a large fleet?
basics
~20 sAn exact two-heap median keeps every sample forever, so memory grows without bound per endpoint per instance, and two instances' results cannot be combined into a global median. Under a fleet memory ceiling, prefer a bounded window or a mergeable quantile sketch.
A teammate proposes Fibonacci heaps for amortized O(1) decrease-key. How do you decide?
basics
~20 sAsk what share of runtime the priority queue owns and how decrease-keys compare with extractions. Fibonacci heaps win on paper, but their pointer overhead and cache behaviour usually lose to an array-backed indexed heap on real inputs.
showing 31–43 of 43