Skip to main content

⛰️ Heap

Heaps (priority queues) excel at "what is the smallest / largest right now?" questions. Top-K, scheduling, merging sorted streams, and running medians all reduce to one or two heaps.

This category contains 2 problems. Use the patterns below to recognize what's being asked, then jump to the problem list at the bottom.


🧠 Key Patterns

  • Top-K Elements — Min-heap of size K for largest-K, max-heap for smallest-K.
  • Merge K Sorted Lists/Streams — Min-heap keyed on current head value.
  • Running Median (two heaps) — Max-heap for lower half, min-heap for upper half.
  • Task Scheduling — Max-heap on remaining frequency.
  • Dijkstra — Min-heap on tentative distance.

⚠️ Common Pitfalls

  • C# PriorityQueue<TElement, TPriority> is a min-heap by default — invert priority for max-heap.
  • Heapify-up vs heapify-down: standard library handles this, but write it once by hand.

📚 Study Resources

📺 Videos

📖 Books

  • Introduction to Algorithms (CLRS) — Ch. 6 (Heapsort), Ch. 19 (Fibonacci heap)

🌐 Articles & References


💻 All Heap Problems