All Patterns

Heap / Priority Queue

Maintain quick access to the min or max element for top-k, merge, and scheduling problems.

When to use

  • Top K elements
  • Merging K sorted lists
  • Running median
  • Task scheduling by priority

When NOT to use

  • Need sorted iteration of all elements
  • Need random access by index

Common traps

  • Using max heap when you need min heap (or vice versa)
  • Not understanding heap size constraints for top-k

Key Invariant

A heap gives O(log n) insert and O(1) peek — use it when you repeatedly need the extreme element

Problems (12)

#91Top K Frequent Elements
medium
#92K Closest Points to Origin
medium
#93Kth Largest Element in an Array
medium
#94Task Scheduler
medium
#95Find K Pairs with Smallest Sums
medium
#158Meeting Rooms II
medium
#196Design Twitter
medium
#266Top K Frequent Words
medium
#276Reorganize String
medium
#277Ugly Number II
medium
#278IPO
hard
#292Minimum Interval to Include Each Query
hard