Heaps and Top K
A heap is the data structure for one question asked over and over: "what is the smallest (or largest) thing right now?" It answers in constant time and absorbs a new item in logarithmic time, which makes it the right tool whenever a problem keeps choosing the best remaining option while new options keep arriving. This lesson is for software engineering and data candidates preparing for a live coding round. It covers the four shapes heap problems take in interviews, with Python code you can trace by hand, and the cases where a plain sort is the better answer.
How heap problems are judged
In a SmartIntervu coding interview the report scores problem solving, correctness, code quality, testing and edge cases, and communication. Heap problems are mostly won on problem solving: the interviewer wants to hear you notice that a full sort does more work than the question needs, and say why a heap of size k is enough. They are lost on correctness details: the wrong heap direction, an empty heap you peek into, or a tuple that cannot be compared.
The AI interviewer lets you drive, then asks for your complexity and your tests. If you sort everything, expect "can you do better when k is small?" If you stall, the first hint is a nudge ("which item would you throw out first?"), and later hints name the heap and its direction. Each hint is counted against the dimension it helped with, the near-solution one most.
What a heap costs
A binary heap is a complete binary tree stored in an array, where every parent is no larger than its children (a min-heap). That one rule gives you these costs:
Peek at the minimum: O(1). It is always at index 0.
Push or pop: O(log n). The new or moved item sifts up or down one level per step.
Build from a list (heapify): O(n), not O(n log n). Most nodes sit near the bottom and barely move.
Find or remove an arbitrary item: O(n). A heap is not sorted beyond the parent rule, so you have to scan.
Python's heapq works on a plain list and is a min-heap only. For a max-heap, push negated numbers. For priorities attached to data, push tuples (priority, tiebreaker, item): the tiebreaker (a counter or an index) keeps Python from ever comparing two items directly, which fails for objects such as tree or list nodes.
The cue
Reach for a heap when the problem says:
"the k largest, smallest, closest or most frequent"
"merge k sorted lists or streams"
"the median (or another order statistic) of a stream"
"repeatedly take the cheapest, earliest or highest-priority item"
The shared signal is repeated selection from a changing set. If you only need one sorted pass over fixed data, the heap is probably overkill.
Shape 1: top k with a heap of size k
To keep the k largest numbers, hold a min-heap of size k. That direction surprises people, so say it out loud: the heap's root is the smallest of your current top k, the one most likely to be pushed out. Each new number only has to beat that root.
import heapq
def top_k_largest(nums: list[int], k: int) -> list[int]:
if k <= 0:
return []
heap: list[int] = []
for x in nums:
if len(heap) < k:
heapq.heappush(heap, x)
elif x > heap[0]:
heapq.heapreplace(heap, x) # pop the root, push x, one sift
return sorted(heap, reverse=True)Trace it on [5, 1, 9, 3, 7] with k = 2. Push 5, push 1: the heap holds 1 and 5. Then 9 beats the root 1 and replaces it (heap: 5, 9). 3 does not beat 5. 7 beats 5 and replaces it (heap: 7, 9). The result is [9, 7].
Time is O(n log k) and extra space is O(k). When k is much smaller than n, that beats sorting's O(n log n), and it works on a stream you cannot hold in memory. The k <= 0 guard matters: without it, heap[0] raises on an empty list.
Here is the difference between two answers to "return the k largest". The weaker one sorts and slices, and when asked for better, pushes everything into a max-heap and pops k times without saying what that costs. The stronger one gives the sort as a baseline, explains why a min-heap of size k is enough before coding (problem solving), uses heapreplace instead of a pop and a push (code quality), traces a small input as above (correctness), raises k = 0, k larger than n and duplicates without being asked (testing and edge cases), and states O(n log k) time and O(k) space against the sort (communication).
The same shape answers "k most frequent": count with a dictionary, then keep a min-heap of (count, value) pairs of size k. "k closest points to the origin" keeps a max-heap of size k on distance (push -distance), because the root must be the farthest of the current best k.
Shape 2: k-way merge
Merging k sorted lists into one is a repeated "which list has the smallest next value?" A heap holding one candidate per list answers it.
def merge_sorted(lists: list[list[int]]) -> list[int]:
heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
heapq.heapify(heap)
merged: list[int] = []
while heap:
value, i, j = heapq.heappop(heap)
merged.append(value)
if j + 1 < len(lists[i]):
heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
return mergedEach entry is (value, list index, position). The list index doubles as the tiebreaker, so two equal values never force Python to compare anything else. With N values in total, the heap never holds more than k entries, so the merge costs O(N log k) time and O(k) extra space. Empty lists are skipped at the start, and an input of no lists returns an empty result.
This is the pattern behind merging sorted files that do not fit in memory, which is a common follow-up: each "list" becomes a file read in chunks, and the heap still holds only k entries.
Shape 3: two heaps for a running median
The median of a stream needs the middle of the data at all times. Split the numbers into a lower half and an upper half:
lowis a max-heap of the smaller half (stored negated).highis a min-heap of the larger half.Invariant: every value in
lowis at most every value inhigh, andlowhas the same size ashighor one more.
class RunningMedian:
def __init__(self) -> None:
self.low: list[int] = [] # max-heap via negated values
self.high: list[int] = [] # min-heap
def add(self, x: int) -> None:
heapq.heappush(self.low, -x)
# Move low's largest to high so the halves stay ordered.
heapq.heappush(self.high, -heapq.heappop(self.low))
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def median(self) -> float:
if len(self.low) > len(self.high):
return float(-self.low[0])
return (-self.low[0] + self.high[0]) / 2Trace it with 5, 2, 10:
Add 5: it goes into
low, moves tohigh, then moves back becausehighgot bigger.lowholds 5 and the median is 5.Add 2: it goes into
low. Low's largest is now 5, which moves tohigh, solowholds 2 andhighholds 5. The median is (2 + 5) / 2 = 3.5.Add 10: it goes into
lowand moves straight tohigh. Nowhighholds 5 and 10, one more thanlow, so 5 moves back.lowholds 2 and 5,highholds 10, and the median is 5.
Each add is O(log n) and median is O(1). State the precondition: median() on an empty stream raises, so either guard it or say the caller adds first.
Shape 4: scheduling by earliest end
Many scheduling problems become easy once you track "which commitment frees up first". To find the minimum number of rooms for a set of meetings, sort meetings by start time and keep a min-heap of end times for the rooms in use.
def min_rooms(meetings: list[tuple[int, int]]) -> int:
ends: list[int] = []
for start, end in sorted(meetings):
if ends and ends[0] <= start:
heapq.heapreplace(ends, end) # reuse the room that freed first
else:
heapq.heappush(ends, end)
return len(ends)On [(0, 30), (5, 10), (15, 20)]: the first meeting takes a room (ends: 30). The second starts at 5, before 30, so it opens a second room (ends: 10, 30). The third starts at 15, after the earliest end 10, so it reuses that room (ends: 20, 30). Two rooms.
The <= treats intervals as half-open: a meeting ending at 10 frees its room for one starting at 10. Ask the interviewer which they mean; it is a cheap clarifying question that the communication score notices. Cost: O(n log n) for the sort plus O(n log n) for heap operations.
When sorting is simpler
A heap is not always the better answer, and saying so shows judgment:
k is close to n: keeping n - k items out is the same work as sorting. Sort once in O(n log n), or keep the smaller side.
The data is fixed and you need everything in order: sort. A heap that you pop n times is a slower sort.
One order statistic on fixed data: quickselect finds the kth largest in O(n) on average. Its worst case is O(n²); a random pivot makes that very unlikely on any input, and median-of-medians pivots guarantee O(n) at a higher constant. Mention it as the alternative even if you code the heap.
The heap wins when items arrive over time, when k is much smaller than n, or when selections and insertions interleave.
Follow-ups to expect
"What if the input is a stream that never ends?" The size-k heap already handles it: memory stays O(k) and the current answer is always available.
"Why a min-heap for the largest k?" Because the item you need to evict is the smallest of the current best, and the root is the only item you can see cheaply.
"How would you remove an item that is no longer valid?" Lazy deletion: leave it in the heap, record it as removed, and skip it when it reaches the top.
"What about ties?" Decide the rule (first seen, smallest value) and encode it in the tuple's second field.
What changes with seniority
A junior candidate is expected to recognize the top-k shape and code it correctly. A mid-level candidate should also explain the O(n log k) bound and handle the empty and k = 0 cases unprompted. A senior candidate compares heap, sort and quickselect for the given constraints, explains why heapify is linear, and extends the solution to streams or data that lives on disk.
Mistakes that cost points
The wrong heap direction. A max-heap of size k for "k largest" shows you the best item, not the one to evict, so the bound breaks. Heapifying all n items and popping k times does work, in O(n + k log n) time, but it needs O(n) memory and the whole input up front; on a stream, the size-k min-heap is the answer.
Forgetting that
heapqis a min-heap. Negate values for max behavior, and negate them back when you read them.Pushing bare objects.
(priority, obj)raises when two priorities tie and the objects cannot be compared. Add a counter as the second field.Peeking at an empty heap.
heap[0]on an empty list raises; guard every peek.Searching the heap.
x in heapis O(n). If you need membership, keep a set alongside.
Practice it
Spend 15 minutes on this drill without looking back at the code:
Write
top_k_frequent(words, k)returning the k most common words, ties broken alphabetically. Decide what goes in the tuple before you type.Trace
RunningMedianby hand on 4, 8, 1, 7 and confirm the medians are 4, 6, 4 and 5.5.Explain out loud, in two sentences, when you would sort instead.
Then take Design an LRU Cache as a live interview. A heap ordered by last use is a tempting first idea; say why it costs at least O(log n) per access and what gets eviction to O(1), which is the same "which item do I evict, and how cheaply can I see it?" question this lesson drills.
Previous in this series: Stacks and Monotonic Stacks. Next: Trees. For the full method around any pattern, see Coding Interviews: A Repeatable Approach.
Practise this in a mock interview
Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.
- Two SumCoding · Easy
- Design an LRU CacheCoding · Medium
- Deploy Services in Dependency WavesCoding · Medium
- Flag Overlapping Maintenance WindowsCoding · Medium
Read next
- Trees
Decide whether information flows down a tree as arguments or up as return values, then write correct DFS, level-order BFS and BST solutions, including iterative traversal for trees too deep for recursion.
9 min read
- Graphs
Model a problem as a graph and pick the right tool (BFS, DFS, topological sort, Dijkstra or union-find) while avoiding the visited-set and recursion-depth bugs that cost correctness points.
9 min read
- Backtracking: Searching Every Option Without Getting Lost
Spot 'list every answer' problems, apply one choose, explore, unchoose template to subsets, permutations, combinations and constraint puzzles, prune early, and state the exponential cost honestly.
9 min read
- Dynamic Programming: From Recursion to a Table
Recognize a dynamic programming problem, apply a five-step recipe (state, recurrence, base case, order, answer), move from memoization to a table and cut its space, and explain the solution out loud.
9 min read
