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.
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.
A quick 3-question quiz on this lesson — instant feedback.
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.
Project-based Data Structures courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Data Structures books — check the publication year so the examples match current versions.
Search Amazon →