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).
heap (the 3 largest so far)
1import heapq2def 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
Variables
Options and trade-offs
| Approach | Time | Space | Notes |
|---|---|---|---|
| Sort everything | O(n log n) | O(1)–O(n) | Simplest; fine if n is small |
| Heap of size k | O(n log k) | O(k) | Best when k ≪ n, and works on streams |
| Quickselect | O(n) average | O(1) | Needs the whole array; O(n²) worst case |
| Bucket sort by count | O(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
Priority queues
A heap keeps the smallest (min-heap) or largest (max-heap) item at the root, and every parent is ≤ its children. Reading the top is O(1); push and pop are O(log n). It's the data structure behind a priority queue.
8 min read →Frequency counting
Walk the input once and keep a count per value in a hash map (or an array of 26 for letters). Comparing or querying counts replaces sorting and nested loops: O(n) time, O(k) space for k distinct values.
7 min read →Merge & quick sort
Both divide and conquer. Merge sort splits in half, sorts each, and merges: always O(n log n), stable, O(n) extra space. Quicksort partitions around a pivot, then sorts each side: O(n log n) on average, O(n²) worst case, in place.
9 min read →