advanced pattern
Top K Elements (Heap)
Use a heap (priority queue) to efficiently find or maintain the K largest/smallest elements.
Time
O(n log k)
Space
O(k)
š§ Mental Model
āA bouncer at an exclusive club with capacity K. Only the top K VIPs stay - when someone new arrives, compare with the least VIP and swap if needed.ā
Verbal cue: Keep K best, replace the worst if something better comes.
šÆRecognition Triggers
When you see these patterns in a problem, consider this approach:
k largestk smallestk most frequentk closesttop kstreaming data
š”Interview Tips
- 1For k largest, use min-heap; for k smallest, use max-heap
- 2QuickSelect is O(n) average but O(n²) worst case - mention trade-off
- 3Streaming use case: heap shines when data arrives one at a time
ā ļøCommon Mistakes
- āUsing max-heap when min-heap is needed (and vice versa)
- āForgetting Python heapq is min-heap only
- āNot handling ties correctly in frequency problems