What is Heap?
Heap is a complete binary tree that maintains the heap property: parent is always smaller (min-heap) or larger (max-heap) than children. It provides O(log n) insertion and O(1) access to min/max.Quick Recognition: If you need k largest/smallest, merge sorted lists, or continuously find min/max, think Heap!
Pattern Recognition Checklist
Use Heap When
- Need k largest/smallest elements
- Merge k sorted lists/arrays
- Continuously track min/max
- Priority-based processing
- Median from data stream
Don't Use When
- Need sorted order (use sort)
- Need arbitrary access by index
- Single min/max needed once
- Memory is very constrained
When to Use
Top K Elements
Find k largest/smallest elements
Merge K Lists
Merge multiple sorted sequences
Scheduling
Process by priority, deadlines
Median Finding
Running median with two heaps
Pattern Variations
1. Kth Largest Element
2. Top K Frequent Elements
3. Merge K Sorted Lists
4. Find Median from Data Stream
5. K Closest Points to Origin
Classic Problems
1. Kth Largest Element
1. Kth Largest Element
Pattern: Min-heap of size kKey: Top of min-heap is kth largest after processing all
2. Merge K Sorted Lists
2. Merge K Sorted Lists
Pattern: Min-heap of list headsKey: Always pop smallest, push its next element
3. Find Median from Data Stream
3. Find Median from Data Stream
Pattern: Two heaps (max for small, min for large)Key: Keep heaps balanced, median from tops
4. Task Scheduler
4. Task Scheduler
Pattern: Max-heap for most frequent tasksKey: Process most frequent first with cooldown
Common Mistakes
The Counter-Intuitive Heap Choice
This confuses many beginners:Complexity Quick Reference
Interview Problems by Company
- Medium
- Hard
Interview Tips
How to Explain Your Approach
How to Explain Your Approach
Script for interviews:
- “Since I need the k largest, I’ll use a min-heap of size k.”
- “I’ll iterate through all elements, pushing each to the heap.”
- “When heap size exceeds k, I pop the smallest.”
- “After processing all, the heap contains the k largest.”
- “Time is O(n log k), space is O(k).”
When Interviewer Says...
When Interviewer Says...
Python Heap Gotchas
Python Heap Gotchas
Python’s For custom objects, use tuples:
heapq is a min-heap only. For max-heap:(priority, item)Practice Problems
Practice Roadmap
1
Day 1: K Elements
- Solve: Kth Largest Element, Top K Frequent
- Focus: When to use min vs max heap
2
Day 2: Merging
- Solve: Merge K Sorted Lists, K Pairs with Smallest Sum
- Focus: Multi-source merging
3
Day 3: Two Heaps
- Solve: Find Median from Data Stream
- Focus: Balancing two heaps
4
Day 4: Applications
- Solve: Task Scheduler, Meeting Rooms II
- Focus: Scheduling with heaps