← Back to Index
🔺 Heap Pattern
🧠 When to Use
- Find Kth smallest/largest elements
- Maintain a dynamic top-K list
- Merge multiple sorted arrays/lists
- Continuously track min/max while streaming
- Scheduling problems or cost optimization
⚙️ Java Syntax
// Min-heap
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// Max-heap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
📌 Common Techniques
poll()
– removes and returns top (min or max)
offer(val)
– adds a new element
- Use minHeap when you want the smallest item at top
- Use maxHeap to keep largest at top (e.g., for Kth smallest)
🔥 Popular Problems
📊 Time Complexity
offer()
: O(log n)
poll()
: O(log n)
peek()
: O(1)
🧠 Pro Tips
- Use max-heap when you need to discard smaller elements
- Use a custom comparator for complex objects
- Always track heap size if using for top-K