← Learning Hub
Advanced

Heaps and PriorityQueue

A heap always gives you the smallest (or largest) item quickly: peek is O(1), add and remove are O(log n). Java's PriorityQueue is a min-heap.

A heap gives quick access to the smallest or largest item. PriorityQueue makes it easy to solve top-K, scheduling and merging problems efficiently.

Example
You can edit this code.

Top K items

Keep a min-heap of size k. Anything smaller than the heap's top can't be in the top k:

Example
You can edit this code.

Processing tasks by priority

Example
You can edit this code.
Printing a PriorityQueue directly does not show sorted order - only poll() takes items out in order.
Key points
  • PriorityQueue is a min-heap.
  • Use Collections.reverseOrder() for a max-heap.
  • Keep a heap of size k for top-K.

📝 Test yourself

1. Java's PriorityQueue is by default a...
2. To keep the top 3 largest, what heap do you use?
3. Fill in the comparator for a max-heap:
new PriorityQueue<>(Collections.())