Stage 1 · Code
Heaps & Priority Queues
Top K Elements
Finding K largest/smallest with min/max heap of size K.
K Largest Elements
Use min-heap of size K. Iterate array: push each element, if size > K, pop smallest. At end, heap contains K largest. Time: O(n log K), Space: O(K).
K Smallest Elements
Use max-heap of size K (or min-heap with negated values). Push, pop when size > K. Root is largest of K smallest.
Top K Frequent Elements
Streaming Top K
For unbounded streams, same min-heap of size K works online. O(log K) per element, O(K) space. Cannot get exact top K without storing all (requires reservoir sampling for approximate).
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.