Web Analytics

๐Ÿ”ฅ Heaps & Priority Queue

Intermediate ~30 min read

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

  1. Add new element to end of array
  2. Compare with parent
  3. If smaller (min heap), swap with parent
  4. 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

  1. Save root (min/max value)
  2. Move last element to root
  3. Compare with children
  4. Swap with smaller child (min heap)
  5. 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

Output
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:

  1. Structure: Complete binary tree in array
  2. Property: Parent โ‰ค children (min) or โ‰ฅ (max)
  3. Insert: Add to end, bubble up - O(log n)
  4. Extract: Remove root, bubble down - O(log n)
  5. Heapify: Build heap from array - O(n)
  6. Peek: Get min/max - O(1)
  7. 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!