A min-heap exposes the smallest retained value while leaving other entries only partially ordered. For largest-k selection, that root is the weakest answer candidate, so compare before replacing and sort only when the output needs full order.
Recognize it when A changing collection repeatedly needs its smallest member.
Checking your account…
Heap Code Labs
Mental Model
A heap is a partially ordered binary tree stored in an array. In Python’s min-heap, every parent is
no greater than its children, so the root at index zero is globally minimal. The rest of the array
is not sorted; only the parent-child relation is guaranteed.
The Heap Order Invariant
For index i, children are 2*i + 1 and 2*i + 2. A push repairs one root-to-leaf path, and a pop
moves the last item to the root before repairing one path downward. That gives O(log n) update and
O(1) minimum lookup.
Build and Update a Min-Heap
heapq.heapify(values) transforms a list in O(n) time and mutates it. heappush and heappop are
O(log n). heappushpop performs the combined operation efficiently and may immediately return a
new item smaller than the existing root; heapreplace always removes the current root first and
requires a nonempty heap.
Build and Consume a Min-Heap
Reference
import heapq
def consume_smallest(values, additions):
heap = values.copy()
heapq.heapify(heap)
popped = []
for value in additions:
heapq.heappush(heap, value)
popped.append(heapq.heappop(heap))
return popped, sorted(heap)
Practice
Implement consume_smallest(values, additions). Heapify a copy, then push each addition and pop the current minimum; return popped values and sorted remaining values.
Public tests
Verify minimum extraction after pushes
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Build and Consume a Min-Heap
import heapq
def consume_smallest(values, additions):
heap = values.copy()
heapq.heapify(heap)
popped = []
for value in additions:
heapq.heappush(heap, value)
popped.append(heapq.heappop(heap))
return popped, sorted(heap)
The heapq documentation(opens in a new tab)
is explicit that the API is a min-heap. Max-priority code traditionally negates numeric priorities;
state that representation instead of mentally reversing comparisons in scattered places.
Keep a Bounded Top K
To retain the k largest values, use a min-heap of at most k candidates. Its root is the weakest
retained candidate. Once full, replace the root only when the new value is larger. The invariant is
that the heap contains the largest min(k, processed) values from the processed prefix.
Keep a Bounded Largest-K Heap
Reference
import heapq
def largest_k_sorted(values, k):
heap = []
for value in values:
if len(heap) < k:
heapq.heappush(heap, value)
elif k and value > heap[0]:
heapq.heapreplace(heap, value)
return sorted(heap)
Practice
Implement largest_k_sorted(values, k). Keep at most k candidates in a min-heap and return retained values in ascending order. k is a nonnegative integer; zero retains no values, and k larger than the input retains every available value.
Public tests
Verify bounded largest candidates
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Keep a Bounded Largest-K Heap
import heapq
def largest_k_sorted(values, k):
heap = []
for value in values:
if len(heap) < k:
heapq.heappush(heap, value)
elif k and value > heap[0]:
heapq.heapreplace(heap, value)
return sorted(heap)
Trace a Root that Represents the Candidate Cutoff
Use the existing largest-k Lab with two candidate slots. Once filled, the root is the cutoff: 8 and 7 improve it, while 1 cannot belong to the best two processed values.
print(largest_k_sorted([6, 2, 8, 1, 7], 2)) followed by print(largest_k_sorted([6, 2], 0))
Step
Executed statement
State
Why
1
heapq.heappush(heap, value)
value = 6; heap = [6]
An unfilled candidate set accepts the first value.
2
heapq.heappush(heap, value)
value = 2; heap = [2, 6]
The root is now the weakest of two retained candidates.
3
heapq.heapreplace(heap, value)
value = 8; heap = [6, 8]
Eight improves the root cutoff and displaces two.
4
elif k and value > heap[0]:
value = 1; heap stays [6, 8]
A weaker new value cannot improve the retained answer.
Seven displaces six; sorting supplies the requested ascending output.
Print
Output
1
[7, 8]
2
[]
The final sorted list is an output choice; the heap needs only expose its weakest retained candidate during scanning. Duplicates remain separate occurrences, and k zero retains nothing.
Choose a Heap or Sort
Use a heap for repeated best-item extraction, streaming top k, or a changing frontier. Sort when all
items are known and the complete order is required; sorting is often simpler and costs O(n log n).
For one kth selection, quickselect may offer better average time but has a more delicate invariant.
Heap Ordering and Candidate Mistakes
Reading the heap array as sorted gives wrong second/third-order results.
Pushing every item for top k wastes O(n) space instead of O(k).
Negated max-heap tuples need consistent signs in every comparison and returned value.
Equal tuple priorities compare later fields, which may be non-comparable objects.
Calling heapreplace on an empty heap raises an error.
Explain It in an Interview
Name the root meaning and the candidate invariant. Explain which single path an update repairs.
Distinguish O(n) heapify from n separate O(log n) pushes, and state whether final sorting adds
O(k log k). Avoid claiming the internal array is ordered beyond the heap property.
Learn this shape by heart; most problems in this family change only one or two lines of it.
Two heaps for the median
Push through small to large, then rebalance.
Numbers arrive one at a time and you need the median at any moment.
Trigger words
running median
median of a stream
median at any time
sliding window median
import heapq
class RunningMedian:
def __init__(self):
self.small = [] # max-heap of the lower half (stored as negatives)
self.large = [] # min-heap of the upper half
def add(self, num):
heapq.heappush(self.small, -num)
heapq.heappush(self.large, -heapq.heappop(self.small)) # move the biggest small up
if len(self.large) > len(self.small):
heapq.heappush(self.small, -heapq.heappop(self.large))
def median(self):
if len(self.small) > len(self.large):
return -self.small[0]
return (-self.small[0] + self.large[0]) / 2
Spot it when
'Find median from data stream'.
Sliding median.
Remember
small may hold one extra item; then its top is the median.
Every add is O(log n); median is O(1).
How problems bend it
Odd total only: Return -self.small[0] directly.
Python Version Note
Python 3.11+
These Labs use the min-heap heapq API available in the browser runtime. Negated numeric priorities provide a max-priority representation without requiring newer max-heap helpers.