Heaps & Priority Queues

intermediate20 min

Heap Data Structure

A binary heap keeps the smallest (or largest) element at the root. Java’s PriorityQueue is a min-heap by default; use a reversed comparator for max-heap behavior.

Types of Heaps

  • Max Heap: Parent is always greater than or equal to children
  • Min Heap: Parent is always less than or equal to children
  • Binary Heap: Most common implementation using arrays

Priority Queue in Java

Common Applications

  • Top K Elements: Find k largest/smallest elements
  • Heap Sort: Sorting using heap data structure
  • Dijkstra’s Algorithm: Shortest path in weighted graphs
  • Merge K Sorted Lists: Efficient merging
  • Task Scheduling: Priority-based scheduling

Find Top K Elements