Top K with a Min-Heap
Keep the k largest values seen so far without sorting the whole input.
python, heap, top k, selectionRetain only the strongest candidates
A min-heap exposes its smallest stored value. For the k largest values,
keep at most k items; once full, replace the smallest only when a larger
candidate arrives.
Python illustration
import heapq
def largest_k(values, k):
if not 0 <= k <= len(values):
raise ValueError("k must be between zero and the input length")
if k == 0:
return []
heap = []
for value in values:
if len(heap) < k:
heapq.heappush(heap, value)
elif value > heap[0]:
heapq.heapreplace(heap, value)
return sorted(heap, reverse=True)
print(largest_k([4, 1, 7, 4, 6], 3))
Prepared output: [7, 6, 4].
See the reasoning
Follow the example one step at a time
Keep the three largest occurrences. This is a prepared teaching demonstration, not live code execution.
Fill the heap
input: 4, 1, 7 heap minimum: 1
The first three values fill the min-heap.
Invariant and cost
After each input prefix the heap contains the largest min(k, prefix length)
occurrences seen so far. Equal values are separate occurrences; this is not
the top k distinct values. For 1 <= k <= n, heap work is O(n log(k+1))
and sorting the result adds O(k log k); extra space is O(k). k = 0
returns an empty list. Values must be mutually comparable; the input must
support len for this contract.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
