Web Analytics

๐ŸŒณ Minimum Spanning Tree (MST)

Advanced ~40 min read

You need to connect all cities with cable networks. Some connections are expensive, others cheap. What's the minimum cost to connect all cities? Minimum Spanning Tree finds the optimal network design!

The Connectivity Problem

Given a weighted graph, find a tree that connects all vertices with minimum total edge weight:

Real-World Applications

  • Network Design: Connect all nodes with minimum cable cost
  • Cluster Analysis: Group similar data points
  • Approximation Algorithms: TSP approximation
  • Image Segmentation: Connect similar pixels
  • Circuit Design: Minimize wire connections

Two Algorithms for MST

1. Kruskal's Algorithm

Edge-Based Greedy

  1. Sort all edges by weight
  2. Add smallest edge that doesn't create cycle
  3. Use Union-Find to detect cycles
  4. Repeat until V-1 edges added

Time: O(E log E) - Best for sparse graphs

2. Prim's Algorithm

Vertex-Based Greedy

  1. Start from any vertex
  2. Add minimum edge from MST to non-MST vertex
  3. Use priority queue to find minimum edge
  4. Repeat until all vertices in MST

Time: O(E log V) - Best for dense graphs

See MST Algorithms in Action

Union-Find Data Structure

Used in Kruskal's

  • Find(x): Find root with path compression
  • Union(x, y): Merge sets using union by rank
  • Cycle Detection: If Find(u) == Find(v), edge creates cycle!
  • Time: O(ฮฑ(V)) amortized - Nearly constant!

The Complete Code

Output
Click Run to execute your code

Kruskal vs Prim

When to Use Each

Aspect Kruskal Prim
Approach Edge-based Vertex-based
Time (Sparse) O(E log E) O(E log V)
Time (Dense) O(E log E) O(Vยฒ)
Best For Sparse graphs Dense graphs

Summary

What You've Learned

MST connects all vertices with minimum total weight:

  1. Kruskal: Sort edges, add smallest (no cycle) - O(E log E)
  2. Prim: Start from vertex, add minimum edge - O(E log V)
  3. Union-Find: Efficient cycle detection in Kruskal's
  4. Both are greedy: Optimal solution guaranteed
  5. Applications: Network design, cluster analysis
  6. Key insight: Greedy choice (minimum edge) is always in MST

What's Next?

You've mastered MST! Next, we'll explore Advanced Graph Algorithms - Floyd-Warshall for all-pairs shortest path, strongly connected components, and finding critical network infrastructure!