All Topics

Heaps & Priority Queue

Efficient min/max retrieval — top-K, merge K lists, and scheduling

0/33 solved

Top-K Elements

Efficiently find the K largest/smallest/most frequent elements

O(n log k) O(n + k)

Approach

Use a heap of size K. For K largest elements, maintain a min-heap — when the heap exceeds size K, remove the minimum. After processing all elements, the heap contains the K largest. The top of the heap is the Kth largest.

How to Recognize

1

Problem asks for K largest, smallest, or most frequent elements

2

Need to maintain a running set of top-K items from a stream

3

Phrases like 'kth largest', 'top K frequent', 'K closest points'

4

Sorting works but heap gives better O(n log k)

Pro Tips

For K largest: use a min-heap of size k (smallest of the K largest is at top)

For K smallest: use a max-heap of size k

QuickSelect gives O(n) average but O(n²) worst case; heap is O(n log k) guaranteed

9

Total

2

Easy

7

Medium

0

Hard

Time

O(n log k)

Space

O(n + k)