Master Heap Patterns for DSA + Competitive Programming
A Heap provides O(log n) insert/delete with O(1) access to the smallest (min-heap) or largest (max-heap) element.
Pattern Table
| Pattern | Typical Questions | Trigger |
|---|---|---|
| Priority Queue Basics | Min/max tracking | Heap of size K |
| Top K Elements | Kth largest, top frequent | Min-heap of size K |
| Kth Smallest/Largest | Kth element | Heap + size control |
| Merge K Sorted | Merge K lists | Min-heap of heads |
| Median / Two Heaps | Running median | Max-heap + Min-heap |
| Heap Sort | Sort using heap | Build heap + extract |
Mental Trigger
Smallest/largest K → Top K → Min-heap of size K.
Generic Java Heap Template (Base)
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
minHeap.offer(val); // insert
minHeap.peek(); // smallest
minHeap.poll(); // remove smallest
Recognition Cheat Sheet
| If you see… | Think… |
|---|---|
| Kth largest/smallest | Heap of size K |
| Top K frequent | Freq map + min-heap |
| Merge K sorted lists | Min-heap of heads |
| Running median | Two heaps |
Premium Content
Unlock Heap Patterns and all premium lessons with a subscription.
All premium lessons
Ad-free experience
Priority support
From ₹199.99/year — See plans