Given a weighted undirected graph with V vertices (0 .. V-1) and edges edges[i] = [u, v, w], return the total weight of its minimum spanning tree — the cheapest set of edges that connects every vertex without a cycle. If the graph is disconnected, return the total weight of the minimum spanning forest (an MST per component).
Input: V = 4, edges = [[0,1,1],[1,2,2],[2,3,3],[0,3,4]] Output: 6 Edges 1 + 2 + 3 connect all four vertices; the weight-4 edge would form a cycle.
Input: V = 3, edges = [[0,1,5],[1,2,3],[0,2,1]] Output: 4 Pick weights 1 and 3; skip 5.
- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - 1 <= w <= 10^4 - undirected edges
A minimum spanning tree is the lightest way to connect all vertices. Two greedy algorithms build it:
Prim (grow a tree). Start at a vertex and repeatedly pull the cheapest edge leaving the current tree to a new vertex, using a min-heap of candidate edges. Restart on any unvisited vertex to cover a disconnected graph. O(E log V).
Kruskal (sort edges). Sort all edges by weight and add each one unless it forms a cycle (its endpoints are already connected, checked with union-find). Each added edge joins two trees; you're done after connecting everything. O(E log E).
Both are greedy and both give the same total weight (unique when weights are distinct) — a consequence of the cut property: the lightest edge crossing any cut is safe to include.
“Just the weight, or the edges?”
The total weight.
“What if the graph is disconnected?”
Sum the MST weight of each component (a spanning forest).
I sort edges and add each with union-find unless it makes a cycle (Kruskal), or grow a tree with a min-heap of the cheapest boundary edges (Prim).
Both give the same total weight by the cut property.
Worked example — V = 4, edges [[0,1,1],[1,2,2],[2,3,3],[0,3,4]]
Kruskal: add 1 (0-1), 2 (1-2), 3 (2-3); skip 4 (would cycle) total = 6
The lightest crossing edge is always safe.
Add an edge only if it joins two different sets.
Prim and Kruskal agree on the total.
| Prim (heap) | Kruskal (union-find) | |
|---|---|---|
| Idea | grow a tree by cheapest boundary edge | sort edges, add if no cycle |
| Time | O(E log V) | O(E log E) |
| Best for | dense graphs | sparse graphs |
Both compute the same minimum total weight. Full code is in the Approaches selector below.
Key takeaway
An MST is the lightest cycle-free connector. Kruskal: sort edges, add with union-find unless a cycle. Prim: grow a tree via a min-heap of boundary edges. Both give the same total weight.
kruskal: sort edges; for each (u,v,w): if find(u)!=find(v): union, total += w