Boss lesson · Unit 03
Top K
Keep the k largest of a stream with a tiny heap
What you practise
- A size-k min-heap for the k largest in O(n log k)
- Heap sort in one sentence
Try a question from this lesson
Pick one
A leaderboard keeps only the top 3 scores while millions arrive one at a time. A new score comes in. Which of the three kept scores must it beat to get on the board?
Correct answer
The smallest of the three
Why
A newcomer only has to beat the weakest keeper, and the weakest keeper is the one it replaces. So the hunt for the largest values needs quick access to the smallest of the kept ones: a min-heap.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The boss: top K
The task: from a long stream of numbers, keep the k largest.
Hold a min-heap of at most k keepers. Push every number. Whenever the heap grows past k, pop: that removes the smallest, which is the one that no longer deserves a place. The heap never holds more than k + 1 items, however long the stream.
from heapq import heappush, heappop
def top_k(nums, k):
h = []
for x in nums:
heappush(h, x)
if len(h) > k:
heappop(h)
return hfunction topK(nums, k) {
const h = [];
for (const x of nums) {
push(h, x);
if (h.length > k) pop(h);
}
return h;
}function topK(nums: number[], k: number) {
const h: number[] = [];
for (const x of nums) {
push(h, x);
if (h.length > k) pop(h);
}
return h;
}Python noteheapq is in the standard library and works on a plain list: heappush(h, x) adds x to the min-heap, heappop(h) removes and returns the smallest item.
JavaScript noteJavaScript has no built-in heap. Here push(h, x) adds x to a min-heap array and pop(h) removes and returns its smallest item: two helpers of about ten lines each.
TypeScript noteTypeScript has no built-in heap either: push(h, x) and pop(h) are small helpers over an array. const h: number[] = [] needs the annotation because an empty literal has no element type to infer.
9 more exercises in the app
- 2× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.