Minimum Spanning Tree
You're a city planner. You have V cities and E possible roads, each with a construction cost. You want every city to be reachable from every other city, but you want to minimize the total road cost. You also want no redundant roads — no cycles.
The result is a Minimum Spanning Tree (MST): a subset of exactly V-1 roads that connects all V cities with the minimum possible total weight.
Kruskal's Algorithm
Kruskal's greedy insight: always pick the cheapest available road that doesn't create a cycle. Sort all roads by cost, then greedily add them one by one, skipping any road that would form a loop.
Union-Find detects cycles in \(O(α(n)\)) per check — making Kruskal's very efficient.
Prim's Algorithm
Prim's builds the MST by growing a connected cluster one city at a time. Start with any city. Always add the cheapest road that connects the current cluster to a new city. Use a min-heap to efficiently find the cheapest connecting road.
Kruskal's vs Prim's
Both always produce a valid MST. Kruskal's shines on sparse graphs (few roads) — sorting E edges is cheap when E is small. Prim's shines on dense graphs — the heap only tracks border edges, not all of them.
← → arrow keys to step · click elements to interact