Minimum Spanning Trees (MST)

A Minimum Spanning Tree (MST) of a connected, weighted, and undirected graph is a subset of the edges that connects all the vertices together, without any cycles, and with the minimum possible total edge weight.


1. Core Principles


2. Primary Algorithms

I. Kruskal’s Algorithm (Greedy)

  1. Sort all edges in the graph by weight in non-decreasing order.
  2. Iterate through sorted edges. For each edge, add it to the MST only if it doesn't form a cycle.
  3. Use Disjoint Set Union (DSU) for efficient cycle detection.

II. Prim’s Algorithm (Greedy)

  1. Start with an arbitrary vertex and mark it as visited.
  2. In each step, find the minimum weight edge that connects a visited vertex to an unvisited vertex.
  3. Add the edge and the new vertex to the MST.

3. Complexity Summary

Algorithm Complexity Data Structure
Kruskal's O(E log E) DSU + Sorting
Prim's (Standard) O(V²) Adjacency Matrix
Prim's (Optimized) O(E log V) Adjacency List + Min-Heap

4. Practical Applications

  1. Network Design: Minimizing the amount of cable needed to connect all houses in a neighborhood to a telecommunications network.
  2. Cluster Analysis: Used in Kruskal-based clustering to find "Nearest Neighbors."
  3. Circuit Design: Minimizing the electrical wire length on a motherboard.

Interview Pro-Tips: Prim's vs. Kruskal's

If an interviewer asks which one to use:


Technical Summary

  1. V-1 Edges: The requirement for a spanning tree.
  2. DSU: The engine for Kruskal's algorithm.
  3. Greedy: Both algorithms make locally optimal choices to find the global minimum.
  4. Cycles: The primary constraint that must be avoided during construction.