Priority queues with fast access to min/max
Day 92 of 149
π Full deep-dive with code examples
The Hospital ER Analogy
In an emergency room:
- Patients aren't treated first-come-first-served
- Most critical cases get priority
- The system can keep the most urgent case at the top
Heaps give you instant access to the highest/lowest priority item!
How Heaps Work
Max Heap: Largest is kept on top!
100
/ \
50 80
/ \ /
20 30 60
peek() β 100 (instant!)
pop() β 100, reorganizes to put 80 on top
Key Operations
| Operation | Speed | What It Does |
|---|---|---|
| peek() | O(1) | See top element |
| push() | O(log n) | Add element |
| pop() | O(log n) | Remove top element |
Getting the max/min is INSTANT!
Getting the max/min is very quick.
Types
| Type | Top Element |
|---|---|
| Max Heap | Largest value |
| Min Heap | Smallest value |
Real Uses
- Task scheduling: Most important task first
- Dijkstra's algorithm: Shortest path
- Merge K sorted lists: Efficiently combine
- Median finding: Keep two heaps
In One Sentence
Heaps are tree structures that give instant access to the highest or lowest priority element.
π Enjoying these? Follow for daily ELI5 explanations!
Making complex tech concepts simple, one day at a time.
Top comments (0)