Graph Algorithms

Hard 35 min read

Why Should You Care About Graph Algorithms?

πŸ—ΊοΈ

GPS Navigation

Google Maps uses Dijkstra's algorithm and A* to find the shortest route from your location to destination, processing millions of intersections in milliseconds!

πŸ‘₯

Social Networks

Facebook's friend recommendations use BFS to find mutual connections. LinkedIn uses similar algorithms to show "People you may know"!

🌐

Internet Routing

Every packet sent over the internet uses graph algorithms to find the best path through routers. BGP protocol uses path vector algorithms!

πŸš‡

Public Transit Planning

City planners use minimum spanning trees to design efficient subway systems. Your transit app uses graph algorithms to plan multi-stop journeys!

🧬

Biology & Medicine

Protein interaction networks help discover new drugs. Graph algorithms analyze how diseases spread through populations!

πŸ’Ό

Supply Chain Logistics

Amazon uses maximum flow algorithms to optimize warehouse-to-delivery routes. FedEx routes millions of packages daily using graph algorithms!

Level 1: Graph Basics (Start Here!)

Level 1

What is a Graph? Think of it as a Social Network!

A graph is just a collection of nodes (people) connected by edges (friendships). That's it!

Interactive Graph Builder

Click to add nodes, drag between nodes to create edges!

Nodes: 0 | Edges: 0 | Type: Undirected

Graph Representations

Adjacency List vs Adjacency Matrix
# Adjacency List - Like a phone book! graph = { 'A': ['B', 'C'], # A is friends with B and C 'B': ['A', 'D'], # B is friends with A and D 'C': ['A', 'D'], # C is friends with A and D 'D': ['B', 'C'] # D is friends with B and C } # Adjacency Matrix - Like a friendship grid! # A B C D matrix = [ [0, 1, 1, 0], # A's connections [1, 0, 0, 1], # B's connections [1, 0, 0, 1], # C's connections [0, 1, 1, 0] # D's connections ]

Core Graph Algorithms

Level 2

BFS vs DFS: The Race!

Traversal Visualizer

Watch how BFS and DFS explore the graph differently!

Order: -

Queue/Stack: -

Dijkstra's Shortest Path

Shortest Path Finder

Click two nodes to find the shortest path between them!

Path: -

Distance: -

BFS Implementation - Level by Level
from collections import deque def bfs(graph, start): """ Breadth-First Search - Explore level by level Like ripples in water! """ visited = set([start]) queue = deque([start]) order = [] while queue: node = queue.popleft() # Take from front order.append(node) for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append(neighbor) return order # Example usage graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': [], 'F': [] } result = bfs(graph, 'A') # Output: ['A', 'B', 'C', 'D', 'E', 'F']

Practice Problems

Practice Time!

Problem Set: From Easy to Hard

E

Easy: Connected Components

Count the number of disconnected "islands" in a graph.

πŸ’‘ Hint

Use BFS/DFS from each unvisited node!

M

Medium: Cycle Detection

Detect if a graph contains a cycle.

πŸ’‘ Hint

In DFS, if you visit a node that's already in the current path, you found a cycle!

H

Hard: Network Delay Time

Find the minimum time for a signal to reach all nodes in a network.

πŸ’‘ Hint

Use Dijkstra's algorithm and return the maximum distance!

Common Graph Patterns

  • Island Problems: Use DFS/BFS on grids
  • Shortest Path: Dijkstra for weighted, BFS for unweighted
  • Cycle Detection: DFS with colors or Union-Find
  • Topological Sort: DFS or Kahn's algorithm
  • Minimum Spanning Tree: Kruskal's or Prim's

Common Mistakes

  • Forgetting to mark nodes as visited
  • Using DFS when BFS would find shortest path
  • Not handling disconnected components
  • Infinite loops in graphs with cycles

Advanced Algorithms

Level 3

Minimum Spanning Tree (MST)

Kruskal's MST Builder

Watch how Kruskal's algorithm builds the minimum spanning tree!

Total Cost: 0

Edges Added: 0

Network Flow - Maximum Flow

Ford-Fulkerson Algorithm
def ford_fulkerson(graph, source, sink): """ Find maximum flow from source to sink Like finding max water flow through pipes! """ def bfs_find_path(source, sink, parent): visited = set([source]) queue = [source] while queue: u = queue.pop(0) for v in graph[u]: if v not in visited and graph[u][v] > 0: visited.add(v) queue.append(v) parent[v] = u if v == sink: return True return False parent = {} max_flow = 0 while bfs_find_path(source, sink, parent): # Find minimum capacity along the path path_flow = float('inf') s = sink while s != source: path_flow = min(path_flow, graph[parent[s]][s]) s = parent[s] # Update residual capacities v = sink while v != source: u = parent[v] graph[u][v] -= path_flow graph[v][u] += path_flow v = parent[v] max_flow += path_flow parent = {} return max_flow

Topological Sorting

Order tasks based on dependencies - like course prerequisites!

πŸ’‘ Real Example: You can't take "Advanced Algorithms" before "Data Structures", and you can't take "Data Structures" before "Intro to Programming". Topological sort gives you the correct order!

Quick Reference Guide

Algorithm Comparison Chart

Algorithm Purpose Time Space When to Use
BFS Shortest path (unweighted) O(V + E) O(V) Level-order, shortest path
DFS Path exploration O(V + E) O(V) Cycle detection, topological sort
Dijkstra Shortest path (weighted) O((V+E)logV) O(V) GPS, network routing
Bellman-Ford Shortest path (negative edges) O(VE) O(V) Currency arbitrage
Floyd-Warshall All-pairs shortest path O(VΒ³) O(VΒ²) Small graphs, transitive closure
Kruskal's Minimum spanning tree O(ElogE) O(V) Network design
Prim's Minimum spanning tree O(ElogV) O(V) Dense graphs

Graph Types

  • πŸ“ Directed: One-way streets
  • ↔️ Undirected: Two-way friendships
  • βš–οΈ Weighted: Distance/cost on edges
  • πŸ”„ Cyclic: Contains loops
  • 🌳 Acyclic: No loops (trees)
  • 🌐 Connected: All nodes reachable

Common Patterns

  • 🏝️ Islands: DFS on grids
  • 🎯 Shortest Path: BFS or Dijkstra
  • πŸ” Cycle Detection: DFS with colors
  • πŸ“š Dependencies: Topological sort
  • 🌲 Minimum Tree: Kruskal's/Prim's
  • πŸ’§ Max Flow: Ford-Fulkerson

Interview Tips

  1. Always clarify: directed or undirected?
  2. Check for cycles and disconnected components
  3. BFS for shortest path in unweighted graphs
  4. DFS for exploring all paths
  5. Consider both adjacency list and matrix representations
  6. Time complexity usually O(V + E) for traversal