Skip to contentKEEP THE CRAFTTHE SANCTUARY

Top K

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.

4 practice exercises8 interview problems

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.

Step Executed statement State Why
Fill first slot if len(heap)<k: heapq.heappush(heap,value) value=6, heap=[6] The heap has not yet reached its permitted size.
Fill second slot heapq.heappush(heap,value); trace.append(sorted(heap)) value=2, snapshot=[2,6] 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

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Bounded largest-value selection and final orderingO(n(1+log(m+1)) + m log(m+1))O(n(1+log(m+1)) + m log(m+1))m=min(k,n). Core heap updates cost O(log(m+1)) each and the final descending sort costs O(m log(m+1)).

Space

O(m) working and result space, where m=min(k,n); trace output stores O(n(m+1)) slots.

Assumptions

  • k is a nonnegative integer; k=0 retains none, and k>n returns all n inputs. The trace sorts each retained heap, costing O(n(1+m log(m+1))) worst case.
  • Python heapq is a min-heap in Python 3.11; its array satisfies parent-child order but is not itself globally sorted.
  • k=0 still scans all n values and the trace saves n empty snapshots; the additive n term covers this boundary.

Invariants Worth Saying Aloud

  1. After each input, the heap contains the largest min(k,processed_count) values seen, including duplicates.
  2. When full, heap[0] is the weakest retained winner; discarding an incoming value <= it preserves the top-k multiset.

When To Use Or Avoid Top K

Use It When

  • Keep the largest min(k,n) numeric values, retaining duplicate values as separate candidates.
  • Use a min-heap for largest winners so a better incoming value can replace the smallest retained one.

Choose Another Tool When

  • Use full sorting when all ranks are needed or k is close to n.
  • For k smallest, reverse the root meaning with an appropriate max-heap representation; do not reuse this largest-value condition unchanged.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Replacing the cutoff with a weaker arrival

Unconditional heapreplace turns winners [6, 7] into [1, 7] when a weak value arrives, discarding a better candidate.

Prevent it: Replace a full heap root only if the incoming value improves the chosen objective.

Avoid

heapq.heapreplace(heap,value)

Use instead

if value > heap[0]:
    heapq.heapreplace(heap,value)

Reading an empty zero-k root

When k=0 the heap intentionally stays empty; accessing heap[0] before guarding that case raises IndexError.

Prevent it: Check k or handle zero before comparing against the cutoff.

Avoid

accepted = value > heap[0]

Use instead

accepted = bool(k) and value > heap[0]

Returning heap-array order as descending output

The min-heap [4, 8, 6] is valid but is not a descending list of winners, so reversing or returning it raw violates ordered output.

Prevent it: Sort the retained winners with reverse=True and include that ordering cost.

Avoid

result = heap.copy()

Use instead

result = sorted(heap,reverse=True)

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.