· software-engineers Editorial · Career  · 7 min read

Swe Interview Heap Priority Queue Patterns

Master heap and priority queue interview patterns for 2026: top-K, merge-K, and two-heap median tracking.

Why Heaps Are One of the Highest-ROI Data Structures to Master

Heap and priority queue questions appear disproportionately often in coding interviews relative to how rarely most engineers implement one from scratch on the job. The reason is simple: a heap-based solution is the differentiator between an O(n log k) answer and an O(n log n) or worse brute-force answer for an entire category of “top-K” and “streaming” problems, and interviewers use these problems specifically to test whether you recognize the pattern rather than defaulting to sorting everything.

If you learn to recognize five or six recurring heap patterns, you can solve a large fraction of medium and hard problems on LeetCode-style platforms and in live interviews at companies from mid-size startups through FAANG. For a structured 2026 problem set organized exactly this way — by pattern, not by random difficulty — see The 0-to-1 SWE Interview Playbook (https://www.amazon.com/dp/B0H256Z1MF?tag=sirjohnnymai-20), which dedicates a full section to heap-based patterns with worked solutions.

Heap Fundamentals You Must Say Out Loud in the Interview

A binary heap is a complete binary tree stored as an array, satisfying the heap property: in a min-heap, every parent node is less than or equal to its children (the reverse for a max-heap). This gives you:

  • O(1) access to the min (or max) element — it’s always at the root.
  • O(log n) insertion and O(log n) extraction, because you only need to traverse the height of the tree, not the whole structure.
  • O(n) to build a heap from an unsorted array (using the bottom-up heapify algorithm) — this is a common interview gotcha, since naive intuition suggests O(n log n).

Most languages have a built-in priority queue: Python’s heapq (min-heap only, negate values for max-heap behavior), Java’s PriorityQueue, C++‘s priority_queue. Know your language’s default (min vs max) cold — getting this backwards under interview pressure is a common and easily avoidable mistake.

Pattern 1: Top-K Elements

The most common heap pattern: find the K largest (or smallest, or most frequent) elements in a collection. The trick that trips up candidates who haven’t seen this pattern: to find the K largest elements efficiently, you maintain a min-heap of size K, not a max-heap.

Why: you want to be able to cheaply discard the smallest of your current top-K candidates whenever a new, larger element arrives. A min-heap gives you O(1) access to that current smallest “gatekeeper” value, and each insertion/eviction is O(log K). This gives you O(n log K) overall, which beats sorting the whole array (O(n log n)) whenever K is meaningfully smaller than n.

Classic variants: “Top K Frequent Elements” (build a frequency map first, then heap on frequency), “Kth Largest Element in an Array” (same min-heap-of-size-K trick), “K Closest Points to Origin” (heap on squared Euclidean distance to avoid unnecessary sqrt calls).

Pattern 2: Merge K Sorted Lists/Arrays

When you need to merge K already-sorted sequences into one sorted output, a heap gives you an efficient way to always know which of the K current “frontier” elements is smallest without repeatedly scanning all K lists.

The approach: push the first element of each of the K lists into a min-heap, tagged with which list it came from. Repeatedly pop the minimum, add it to the output, and push the next element from that same list (if one exists). This runs in O(n log K) where n is the total number of elements across all lists — dramatically better than the naive O(nK) approach of scanning all K heads on every step.

This pattern generalizes directly to real systems: merging sorted results from K shards in a distributed database, or merging K sorted log files by timestamp, both use exactly this heap-based k-way merge.

Pattern 3: Two Heaps for Running Median

Finding the median of a data stream (numbers arriving one at a time, need median after each insertion) is a canonical “why does this need two heaps” interview question. The solution maintains two heaps:

  • A max-heap holding the smaller half of the numbers seen so far.
  • A min-heap holding the larger half.

Balanced so their sizes differ by at most 1. The median is either the top of the larger heap (if sizes are unequal) or the average of both tops (if sizes are equal). Insertion is O(log n) — you push to one heap, then potentially rebalance by moving the top element to the other heap if the size invariant is violated.

This pattern generalizes to any “running statistic that requires knowing both extremes of an ordered set as it grows” problem, including sliding-window median variants.

Pattern 4: Heap for Scheduling and Interval Problems

Problems like “meeting rooms II” (minimum number of conference rooms needed given a list of meeting intervals) use a min-heap to track end times of currently “in progress” meetings. Sort meetings by start time, then for each new meeting, check if the earliest-ending meeting in the heap has already finished (its end time <= the new meeting’s start time) — if so, pop it and reuse that room; otherwise push a new end time onto the heap. The heap size at any point tells you the number of rooms in concurrent use, and its maximum size across the whole run is your answer.

This same pattern underlies real task scheduler design (e.g., a job scheduler that needs to know how many worker slots are needed given overlapping job durations).

Comparison Table: Heap Patterns at a Glance

PatternHeap Type UsedTime ComplexityCanonical Problem
Top-K largestMin-heap of size KO(n log K)Kth Largest Element in an Array
Top-K frequentMin-heap of size K on frequencyO(n log K)Top K Frequent Elements
K closest pointsMax-heap of size K on distanceO(n log K)K Closest Points to Origin
Merge K sorted listsMin-heap of size KO(n log K)Merge K Sorted Lists
Running medianTwo heaps (max + min)O(log n) per insertionFind Median from Data Stream
Meeting rooms / schedulingMin-heap on end timesO(n log n) overallMeeting Rooms II
Dijkstra’s shortest pathMin-heap on distanceO((V+E) log V)Network Delay Time
Task scheduling with cooldownMax-heap on remaining countO(n log 26) practicallyTask Scheduler

Common Mistakes That Cost Points in Interviews

  • Using a max-heap when you need a min-heap of size K (or vice versa) for top-K problems — always double-check which heap gives you the cheap “evict the current worst candidate” operation.
  • Forgetting Python’s heapq is min-heap only — candidates frequently forget to negate values for max-heap simulation and get confused mid-interview when results come out backwards.
  • Not maintaining the size invariant in the two-heap median pattern — failing to rebalance after every insertion silently breaks correctness in a way that’s easy to miss on small test cases but fails on longer streams.
  • Reaching for a heap when a simpler approach exists — if K equals n (you need everything sorted, not just the top K), a heap approach is strictly worse than just sorting; recognizing when NOT to use a heap is part of demonstrating real judgment.
  • Ignoring that heapify is O(n), not O(n log n) — this matters when an interviewer asks you to justify overall complexity precisely, especially in staff-level interviews where complexity analysis is scrutinized closely.

FAQ

Q: How do I know when a problem calls for a heap versus a different data structure entirely? A: Look for these signals: you need repeated access to a min or max as the data set changes over time (streaming, running statistics), you need the top/bottom K elements without fully sorting everything, or you’re merging multiple sorted sequences. If the problem instead needs fast lookups by key, a hash map is more appropriate; if it needs ordered traversal with range queries, a balanced BST or sorted structure is often better.

Q: Is it ever better to just sort instead of using a heap? A: Yes — if you need the full sorted order of all elements (not just the top K), sorting is simpler to implement and has the same or better asymptotic complexity. Heaps win specifically when K is much smaller than n, or when data arrives incrementally and you need an efficient running answer rather than a one-time batch sort.

Q: Do I need to implement a heap from scratch in interviews, or can I use the built-in library? A: Almost always the built-in library (heapq, PriorityQueue) is acceptable and expected — interviewers are testing pattern recognition and complexity analysis, not your ability to hand-roll a binary heap. Being asked to implement a heap from scratch is a distinct, less common question type, usually reserved for more fundamentals-focused rounds.

For a full worked problem set covering these heap patterns plus 40+ other recurring interview categories, see The 0-to-1 SWE Interview Playbook (https://www.amazon.com/dp/B0H256Z1MF?tag=sirjohnnymai-20).

Back to Blog

Related Posts

View All Posts »