Find the MST Weight

medium

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).

Hints

An MST is the lightest set of edges connecting all vertices without a cycle.
Kruskal: sort edges and add each with union-find unless it forms a cycle.
Prim: grow a tree from a vertex, always adding the cheapest boundary edge via a min-heap.

Common doubts

The cut property: for any partition of the vertices, the lightest edge crossing it belongs to some MST, so adding it never overshoots.
Both give the same weight. Kruskal (sort + union-find) suits sparse graphs; Prim (heap) suits dense ones.
There's no single spanning tree; return the minimum spanning forest — the sum of each component's MST.

Interview follow-ups

Record each edge you add during Kruskal or Prim.
Sort edges descending (Kruskal) or use a max-heap (Prim).

Fun facts

  • Kruskal's cycle check is the textbook application of union-find.
  • Borůvka's algorithm (1926) predates both and parallelises nicely.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
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.
Example 2
Input: V = 3, edges = [[0,1,5],[1,2,3],[0,2,1]]
Output: 4
Pick weights 1 and 3; skip 5.
Constraints

- 1 <= V <= 10^5 - 0 <= edges.length <= 10^5 - 1 <= w <= 10^4 - undirected edges

Solve this problem →