Algorithms Playbook
PatternTime O(n log k) · Space O(k)8 min read

Top-K: the K largest without sorting everything

Keep a heap of size K to find the largest (or most frequent) items in one pass, and when quickselect or bucket sort beats it.

In short

To get the K largest, keep a min-heap of size K: its root is the weakest winner. For each number, if it beats the root, replace it. Cost: O(n log k) time, O(k) space.

The counter-intuitive trick

For the K largest you use a min-heap. The root is the smallest of the current top K: the one every newcomer has to beat. The heap never grows beyond K, so each operation is O(log k).

Top-K largest with a min-heap of size k
Speed
041922374551163

heap (the 3 largest so far)

0∅
k = 3
1import heapq
2def top_k(nums, k):
3 heap = []
4 for x in nums:
5 if len(heap) < k:
6 heapq.heappush(heap, x)
7 elif x > heap[0]:
8 heapq.heapreplace(heap, x)
9 return heap
Find the 3 largest numbers. Keep a MIN-heap of size 3: its root is the smallest of the current top 3, the one to beat.

Variables

k3
Step 1/12· Heap ops: 0
Counter-intuitive but right: to keep the K largest you use a MIN-heap, so the weakest of the winners is always at the root, ready to be replaced.

Options and trade-offs

ApproachTimeSpaceNotes
Sort everythingO(n log n)O(1)–O(n)Simplest; fine if n is small
Heap of size kO(n log k)O(k)Best when k ≪ n, and works on streams
QuickselectO(n) averageO(1)Needs the whole array; O(n²) worst case
Bucket sort by countO(n)O(n)For top-K frequent: counts are bounded by n
  • Top K frequent elements: count with a hash map, then a heap of size K keyed by count (or bucket by count).
  • K-th largest element: the root of the size-K min-heap is the answer.
  • K closest points: a *max*-heap of size K keyed by distance: evict the farthest.
  • Merge K sorted lists: a min-heap holding the current head of each list.

Key takeaways

  • 01K largest = min-heap of size K; K smallest = max-heap of size K.
  • 02O(n log k) time, O(k) space, works on streams.
  • 03Top-K frequent: hash map for counts, then heap or bucket sort.
  • 04Mention quickselect (O(n) average) as the follow-up.

Check your understanding

1 of 3

To keep the K largest numbers, which heap do you use?

Related topics