Heaps, Top-K, And Streaming Selection
Asked of: Software Engineer
Last updated

What's being tested
Heaps, top-k selection, and streaming aggregation test whether you can avoid full sorting when only a small ranked subset is needed. Interviewers look for correct data-structure choice, precise O(...) complexity, and clean handling of ties, duplicates, and incremental updates.
Patterns & templates
-
Top-k frequent elements — count with
HashMap, maintain size-kmin-heap;O(n log k)time,O(n)space. -
Bucket sort for frequencies — when counts are integers in
[1,n], use frequency buckets forO(n)time; watch memory tradeoffs. -
Streaming median — use max-heap for lower half and min-heap for upper half; rebalance so sizes differ by at most one.
-
Per-key top-k — map each key to a bounded min-heap, e.g. top three scores per student;
O(n log k)with tinyk. -
Meeting rooms — sort intervals by start time, track earliest ending meeting in min-heap; heap size equals rooms needed.
-
Tie-breaking discipline — define comparator explicitly: frequency first, then value/order if required; avoid nondeterministic heap output.
-
Heap API fluency — know
heappush,heappop,heapreplace, and negative-value max-heap simulation inPython.
Common pitfalls
Pitfall: Sorting everything with
O(n log n)when a bounded heap givesO(n log k)and is the expected optimization.
Pitfall: Forgetting to rebalance two heaps in streaming median after every insert, causing wrong medians after skewed input.
Pitfall: Returning heap contents directly when the problem requires sorted output; pop or sort the final
kelements if order matters.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Featured in interview prep guides
Practice questions
- Compute conflicts and minimum meeting roomsApple · Software Engineer · Technical Screen · hard
- Solve 15 common Apple coding questionsApple · Software Engineer · Technical Screen · medium
- Solve interval, grid-fill, and heap tasksApple · Software Engineer · Technical Screen · medium
- Compute minimum required meeting roomsApple · Software Engineer · Technical Screen · Medium
- Implement rotation, LRU cache, streaming median, cycle detectionApple · Software Engineer · Onsite · Medium
- Find top-k frequent elements efficientlyApple · Software Engineer · Technical Screen · Medium
- Compute top three scores per studentApple · Software Engineer · Technical Screen · Medium
- Maximize funds with capital-gated projectsApple · Software Engineer · Technical Screen · Medium
Related concepts
- Heaps, Priority Queues, and Top-K SelectionCoding & Algorithms
- Top-K Selection, Heaps, And RankingCoding & Algorithms
- Top-K, Heaps, Quickselect, And Frequency AnalysisCoding & Algorithms
- Top-K Selection And Order StatisticsCoding & Algorithms
- Heaps And Selection AlgorithmsCoding & Algorithms
- Greedy, Heaps, And Scheduling OptimizationCoding & Algorithms