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