BeginnerCoder

Lesson 21 — Min-heap: keep the top k

Keep the top k with a small heap

To find the 3 highest scores in a huge stream, you do not need to sort everything. Keep a min-heap of size k: its smallest item (h[0]) is the weakest of your current top k. For each new score, push it; if the heap grows past k, pop the smallest. What remains is the top k.

heapq.heappush(best, price)
if len(best) > limit:
    heapq.heappop(best)   # drop the smallest

This costs O(n log k) and only k items of memory.

Why it matters: leaderboards, "top 10 products" and trending topics are computed this way over data too big to sort.

Want it another way?
Task

Write the two steps from the theory inside the loop. Expected: [91, 88, 77].

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Data Structures

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.