๐ฅ Heaps & Priority Queue
Imagine a hospital emergency room. Patients aren't treated first-come-first-served - they're prioritized by urgency. Critical cases go first, minor injuries wait. This is exactly what a heap does - it efficiently manages priorities!
The Priority Problem
Many real-world scenarios need priority-based processing:
Real-World Priority Systems
- Emergency Room: Treat critical patients first
- Task Scheduler: Run high-priority tasks first
- Network Routing: Send urgent packets first
- Event Systems: Process events by timestamp
We need a data structure that can:
- Quickly find the highest priority item
- Efficiently add new items
- Remove the highest priority item
The Heap Solution
What is a Heap?
A heap is a complete binary tree with a special property:
- Min Heap: Parent โค children (root is minimum)
- Max Heap: Parent โฅ children (root is maximum)
Key insight: Root is always the min/max - O(1) access!
See the Structure
Why Heaps Are Brilliant
The Magic of Array Storage
Heaps are stored in arrays - no pointers needed!
Parent of i: (i - 1) / 2
Left child of i: 2i + 1
Right child of i: 2i + 2
This makes heaps incredibly space-efficient!
Basic Operations
1. Insert (Bubble Up)
How It Works
- Add new element to end of array
- Compare with parent
- If smaller (min heap), swap with parent
- Repeat until heap property restored
Time: O(log n) - at most h swaps where h = height
2. Extract Min/Max (Bubble Down)
How It Works
- Save root (min/max value)
- Move last element to root
- Compare with children
- Swap with smaller child (min heap)
- Repeat until heap property restored
Time: O(log n)
3. Heapify (Build Heap)
Build Heap from Array
Start from last non-leaf node, heapify down
Time: O(n) - surprisingly faster than n inserts!
Why O(n)? Most nodes are near bottom, require few swaps
The Complete Code
Click Run to execute your code
Real-World Applications
Where Heaps Are Used
- Priority Queues: Task scheduling, event systems
- Dijkstra's Algorithm: Finding shortest paths
- Heap Sort: O(n log n) sorting
- Top K Problems: Find K largest/smallest elements
- Median Maintenance: Running median from stream
- Operating Systems: Process scheduling
Min Heap vs Max Heap
When to Use Each
Min Heap:
- Find minimum quickly
- Dijkstra's algorithm (shortest path)
- Merge K sorted lists
Max Heap:
- Find maximum quickly
- Find K largest elements
- Heap sort (descending order)
Summary
What You've Learned
Heaps are efficient priority-based data structures:
- Structure: Complete binary tree in array
- Property: Parent โค children (min) or โฅ (max)
- Insert: Add to end, bubble up - O(log n)
- Extract: Remove root, bubble down - O(log n)
- Heapify: Build heap from array - O(n)
- Peek: Get min/max - O(1)
- Applications: Priority queues, sorting, algorithms
What's Next?
You've mastered heaps! Next, we'll explore heap applications - solving real problems like finding K largest elements, heap sort, and maintaining running median!
Enjoying these tutorials?