Pattern Recognition Drill
Medium Heaps
The Problem
Given an array of integers and k, return the k most frequent elements.
What approach would you use?
Think about it before scrolling down.
Count with Counter, then use min-heap of size k. Push all, pop when size > k. O(n log k).
Bucket sort by frequency: create buckets[freq] = [elements]. Scan from highest bucket. O(n).
Common Trap
Sorting all elements by frequency is O(n log n). Heap of size k is O(n log k) — better when k << n.