Retain the k largest values with a bounded min-heap whose root is the weakest winner. Define duplicate, zero-k and output-order contracts before choosing selection or sorting, and distinguish diagnostic sorting from the core scan.
Recognize it when Only a small number of largest candidates are required rather than every rank.
Checking your account…
Top K Code Labs
Name Which Values Win
Top-k is a selection question, not one fixed algorithm. These Labs retain the largest values, including duplicates. A bounded min-heap makes the smallest retained value easy to remove. Keeping the smallest values would need the opposite root meaning; clarify the objective before choosing signs or comparisons.
Let the Root Be the Weakest Winner
Fill the heap until k items are retained. Once full, a value no larger than the root cannot improve the winners; a larger value replaces that weakest retained item. The trace displays sorted heap contents to make the chosen multiset readable. Its displayed order is not the heap’s physical array order.
Trace a Size-K Heap
Reference
import heapq
def top_k_trace(values,k):
heap=[]; trace=[]
for value in values:
if len(heap)<k: heapq.heappush(heap,value)
elif k and value>heap[0]: heapq.heapreplace(heap,value)
trace.append(sorted(heap))
return trace
Practice
Implement top_k_trace(values, k). Return the sorted min-heap contents after each input value is considered. k is a nonnegative integer; retain the largest min(k, len(values)) values, including duplicates.
Public tests
Keep the root as the weakest winner
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Trace a Size-K Heap
import heapq
def top_k_trace(values,k):
heap=[]; trace=[]
for value in values:
if len(heap)<k: heapq.heappush(heap,value)
elif k and value>heap[0]: heapq.heapreplace(heap,value)
trace.append(sorted(heap))
return trace
Keep Equal Winners and Ignore a Weak Arrival
Run the existing trace on [6, 2, 7, 7, 1] with k=2. Sorted snapshots expose the retained multiset after each arrival.
2 is the weakest winner while only two values have appeared.
Improve cutoff
elif k and value>heap[0]: heapq.heapreplace(heap,value)
value=7, snapshot=[6,7]
7 replaces the weaker retained 2.
Keep a duplicate winner
elif k and value>heap[0]: heapq.heapreplace(heap,value)
value=7, snapshot=[7,7]
The new 7 improves the root 6; duplicate values are separate inputs.
Ignore 1
trace.append(sorted(heap))
value=1, snapshot=[7,7]
A value below the cutoff cannot improve the retained multiset.
Return observations
return trace
five sorted snapshots
Sorting belongs to diagnostic display, not the heap invariant itself.
Print
Output
print(top_k_trace([6, 2, 7, 7, 1], 2))
[[6], [2, 6], [6, 7], [7, 7], [7, 7]]
Separate Selection from Output Ordering
The answer Lab performs the same bounded selection and returns a descending sort of the winners. A heap property only identifies the root and parent-child relation, so returning its raw array does not fulfill an ordered-output contract. k=0 returns no winners; k larger than the input retains every available value rather than inventing additional items.
Return the K Largest Values
Reference
import heapq
def k_largest(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,reverse=True)
Practice
Implement k_largest(values,k). Return the k largest values in descending order without mutating input. k is a nonnegative integer; retain the largest min(k, len(values)) values, including duplicates.
Public tests
Return only the strongest candidates
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Return the K Largest Values
import heapq
def k_largest(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,reverse=True)
Choose Sorting or Selection with Honest Costs
For m=min(k,n), the core scan uses O(n(1+log(m+1))) time and O(m) space, then pays O(m log(m+1)) for sorted output. The trace sorts every intermediate heap, which can cost O(nm log(m+1)) plus O(n) observations. Full sorting is often simpler when k approaches n; quickselect is useful for average-linear partitioning but does not directly order the selected winners.
Defend the Cutoff in an Interview
Explain why the root is the discard boundary, why a weaker arrival cannot return later, and whether equal values count separately. Check zero k, duplicate winners and an incoming value below the root. State the final ordering cost before adapting the pattern to kth-largest selection, which may need only the root rather than a sorted winner list.
Template To Memorize
Learn this shape by heart; most problems in this family change only one or two lines of it.
Top k with a heap
Keep k, kick the smallest.
You need the k largest, smallest, closest or most frequent items.
Trigger words
k-th largest
top k
k closest
k smallest
largest two stones
smallest free seat
import heapq
def k_largest(nums, k):
heap = [] # min-heap with the k largest values so far
for num in nums:
heapq.heappush(heap, num)
if len(heap) > k:
heapq.heappop(heap) # drop the smallest
return heap # heap[0] is the k-th largest
Spot it when
'k-th largest', 'top k frequent', 'k closest points'.
A stream of numbers.
Remember
Python's heapq is a min-heap; push negative values to simulate a max-heap.
Size-k heap: O(n log k) time, O(k) space.
How problems bend it
k closest points: Push (-distance, point) so the farthest point is popped first.
Top k frequent: Count first, then push (count, value) pairs.
Always serve the smallest next: No size limit: push every candidate and heappop whenever you need the current smallest (free seats, rooms that end first).
Most frequent first, with a cooldown: Pop the largest count from a max-heap, park it in a queue with the time it may return, and push it back when that time comes.
Python Version Note
Python 3.11+
Python heapq is a min-heap in Python 3.11; its array satisfies parent-child order but is not itself globally sorted.