Keep the top three of a stream
transcript
Scores pour in all day, from every student. You want the top three. You cannot keep every score. You cannot sort them all, either. A tiny heap does it. Watch it work.
Keep a min-heap of size three. Seven, two and nine arrive, and fit in the heap. Four arrives. The heap has four. Pop the smallest, which is two. Two leaves the heap. Eight arrives. Pop four. The top is the third largest.
The weakest of the best is on top. A better score pushes it out. So you pop the smallest. The top is the third largest.
Each score costs log k. The memory is only k scores, however long the stream. A full sort costs n log n. With a small k, it costs little more than one pass.
Push each score, then pop the smallest. The heap never grows past size k. Try top k in the sandbox. Full breakdown in the lecture.