Heaps and Graphs

📖 Introduction

Heaps and graphs are two fundamental non-linear data structures that appear constantly in real-world applications. Every time I use a task scheduler with priorities, implement a social network feature, or work with network routing, I'm leveraging these structures.

Heaps gave me an elegant way to always access the "most important" element efficiently. Graphs taught me to model relationships between entities—from dependencies in build systems to recommendations in e-commerce.


🏔️ Heaps

A heap is a complete binary tree that satisfies the heap property.

Heap Property

spinner
# Min Heap: parent ≤ children (root is minimum)
# Max Heap: parent ≥ children (root is maximum)

# Array representation (0-indexed):
# Parent of i: (i - 1) // 2
# Left child of i: 2 * i + 1
# Right child of i: 2 * i + 2

Heap Implementation

Heapify: Building a Heap

Python's heapq Module

Heap Time Complexity

Operation
Time

peek

O(1)

push

O(log n)

pop

O(log n)

heapify

O(n)

search

O(n)


📊 Heap Problems

Kth Largest Element

Top K Frequent Elements

Merge K Sorted Lists

Find Median from Data Stream


🕸️ Graphs

A graph consists of vertices (nodes) and edges connecting them.

Graph Terminology

spinner

Graph Representations

Comparison

Representation
Space
Check Edge
Get Neighbors
Add Edge

Adjacency List

O(V+E)

O(degree)

O(1)

O(1)

Adjacency Matrix

O(V²)

O(1)

O(V)

O(1)

Edge List

O(E)

O(E)

O(E)

O(1)


🔍 Graph Traversals

Breadth-First Search (BFS)

Explore level by level. Use queue.

Depth-First Search (DFS)

Explore as deep as possible. Use recursion or stack.

BFS vs DFS

Aspect
BFS
DFS

Data Structure

Queue

Stack/Recursion

Shortest Path

Yes (unweighted)

No

Memory

O(width)

O(height)

Use Cases

Level-order, shortest path

Cycle detection, topological sort


📊 Common Graph Problems

Number of Islands

Clone Graph

Course Schedule (Cycle Detection)

Word Ladder

Bipartite Graph


📝 Practice Exercises

Exercise 1: K Closest Points to Origin

chevron-rightSolutionhashtag

Exercise 2: Surrounded Regions

chevron-rightSolutionhashtag

Exercise 3: Network Delay Time

chevron-rightSolutionhashtag

🔑 Key Takeaways

  1. Heaps provide O(log n) insert/remove and O(1) peek for min/max

  2. Python's heapq is a min heap—negate for max heap

  3. Graphs model relationships; choose representation by use case

  4. BFS finds shortest path in unweighted graphs

  5. DFS is better for exploring all paths, cycle detection

  6. Grid problems are often graph problems in disguise


🚀 What's Next?

In the next article, we'll explore sorting algorithms:

  • Comparison-based sorts

  • Stable vs unstable sorting

  • Python's Timsort

  • When to use which algorithm

Next: Article 10 - Sorting


📚 References

  • CLRS Chapter 6: Heapsort

  • CLRS Chapter 22: Graph Algorithms

  • Python heapq module documentation

Last updated