Learning pathsA
Data structures

Heaps and top K

Maintain only the candidates you need.

Understand the problem

A min-heap of size k retains the k largest values seen. Replace its minimum when a larger value arrives. A heap supports fast extremum access, not arbitrary sorted iteration.

Make it concrete

Streaming the top 3 scores keeps only 3 heap entries even if the stream is large.

Trade-offs and pitfalls

Sorting is often simpler for a batch; heaps excel when k is small or input streams.

Check your understanding

Compare O(n log k) heap selection with O(n log n) sorting.

Practice this topic

Your study notes