Skip to main content
General

Heap/Priority Queue problems - when to recognize you need one

Lakshay DesaiLakshay Desai
7/23/2025
10

The clue that you need a heap is usually in the problem statement:

  • "Find the K largest/smallest elements" → Min/Max heap
  • "Merge K sorted lists/arrays" → Min heap
  • "Median of a data stream" → Two heaps
  • "Schedule tasks with priorities" → Max heap
  • "Closest points to origin" → Max heap of size K

Common mistake: Using sorting when a heap would be more efficient.

  • Sorting: O(n log n)
  • Heap of size K: O(n log K) — better when K << n

Python's heapq makes implementation trivial.


heappriority-queuepatternsdsa

Comments (1)

Sign in to join the discussion.
Vandana Pillai
Vandana Pillai10 months ago

I always forget when to use a min heap vs a max heap. Like for 'K largest elements' should I use a min heap or max heap?