MST — Kruskal's Algorithm
Build a minimum spanning tree by taking edges cheapest-first, skipping any that would close a cycle.
Open on GeeksforGeeks ↗Intuition
Sort every edge by weight and walk the list, taking an edge whenever its endpoints are not already connected. Unlike Prim's, the partial result is a forest of separate trees that gradually merge. The only hard question — 'are these two vertices already connected?' — is exactly what Union-Find answers in near-constant time.
Approach
Sort edges by weight
Cheapest first. This is the greedy order, and the sort dominates the runtime at O(E log E).
Union-Find as the cycle test
find(u) == find(v) means both are already in the same tree, so the edge would create a cycle — skip it. Otherwise union them and take the edge.
Stop at V−1 edges
A spanning tree on V vertices has exactly V−1 edges. Finishing with fewer means the graph was disconnected and no spanning tree exists.
Solution & live demo
Edge cases
Fewer than V−1 edges are taken — report no MST.
Any consistent tie-break works; different MSTs may result, all of equal weight.
Endpoints share a root immediately — always skipped.