Lesson 46 of 86IntermediatePro Interactive Lesson

Finding the Top K with a Heap

Use the smallest retained value as the threshold for admitting a new candidate.

Core Intuition & How It Works

To find the K largest elements in a stream of n items without sorting everything, maintain a min-heap of size K. Any element larger than the heap’s minimum replaces it, yielding O(n log k) time and O(k) memory.

In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.

Time & Space Complexity

MetricComplexity
Time ComplexityO(n log k)
Space ComplexityO(k)
Topic ChapterChapter 8: Heaps & Priority Queues
Difficulty LevelIntermediate

Key Pattern to Recognize

Use a min-heap of size K for K largest (and a max-heap of size K for K smallest) so the eviction boundary is always at the root.

Common Pitfalls & Edge Cases

Using a max-heap of size n when k << n, which wastes O(n) memory and O(n + k log n) time on streaming data.

Real-World & Technical Interview Applications

Trending leaderboards, K closest points, top-K frequent queries, and search ranking pipelines.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.