Find the MST weight

Pattern: Minimum spanning tree

medium

A minimum spanning tree joins every vertex using the least total weight. Prim's method grows a tree from vertex 0, always adding the cheapest edge that leaves it; a min-heap of edges makes each step O(log E).

The problem

Given a connected undirected weighted graph, return the total weight of a minimum spanning tree. Vertices are numbered from 0 and each edge is [u, v, weight].

Think first

  • How many edges does the tree have?
  • Which edge is always safe to add next?
  • What stops a cycle?

Hints

    Brute force, and why it fails

    Try every set of n - 1 edges: exponential.

    The key insight

    The cut property: the cheapest edge leaving any part of the graph belongs to some minimum spanning tree, so greedy growth is safe.

    Dry run

    total2

    Take the 5-vertex example with edges 0-1 (2), 0-3 (6), 1-2 (3), 1-3 (8), 1-4 (5), 2-4 (7), 3-4 (9). Start at 0: cheapest edge out is 0-1 (2).

    Step 1 of 3

    The plan

    heap = [(0, 0)]; inTree = none
    while heap: (w, u) = pop; if u in tree: skip
      add u; total += w; push (weight, v) for edges to v outside
    

    Complexity

    Time
    O(E log E)
    Space
    O(V + E)

    Each edge enters the heap at most twice.

    Edge cases

    • A single vertex with no edges.
    • A graph in several pieces.
    • Two vertices joined by one edge.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int spanningTree(int n, int[][] edges) {
            List<List<int[]>> adj = new ArrayList<>();
            for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
            for (int[] e : edges) { adj.get(e[0]).add(new int[]{e[1], e[2]}); adj.get(e[1]).add(new int[]{e[0], e[2]}); }
            boolean[] inTree = new boolean[n];
            PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);   // {weight, vertex}
            pq.add(new int[]{0, 0});
            int total = 0;
            while (!pq.isEmpty()) {                 // Prim: always add the cheapest edge leaving the tree
                int[] top = pq.poll();
                if (inTree[top[1]]) continue;
                inTree[top[1]] = true;
                total += top[0];
                for (int[] e : adj.get(top[1])) if (!inTree[e[0]]) pq.add(new int[]{e[1], e[0]});
            }
            return total;
        }
    }

    C++

    class Solution {
    public:
        int spanningTree(int n, vector<vector<int>>& edges) {
            vector<vector<pair<int, int>>> adj(n);
            for (const vector<int>& e : edges) { adj[e[0]].push_back(make_pair(e[1], e[2])); adj[e[1]].push_back(make_pair(e[0], e[2])); }
            vector<bool> inTree(n, false);
            priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;   // {weight, vertex}
            pq.push(make_pair(0, 0));
            int total = 0;
            while (!pq.empty()) {                   // Prim: always add the cheapest edge leaving the tree
                pair<int, int> top = pq.top();
                pq.pop();
                if (inTree[top.second]) continue;
                inTree[top.second] = true;
                total += top.first;
                for (const pair<int, int>& e : adj[top.second]) if (!inTree[e.first]) pq.push(make_pair(e.second, e.first));
            }
            return total;
        }
    };

    Python

    import heapq
    
    class Solution:
        def spanningTree(self, n: int, edges: list[list[int]]) -> int:
            adj = [[] for _ in range(n)]
            for u, v, w in edges:
                adj[u].append((v, w))
                adj[v].append((u, w))
            in_tree, total, pq = [False] * n, 0, [(0, 0)]   # (weight, vertex)
            while pq:                               # Prim: always add the cheapest edge leaving the tree
                w, u = heapq.heappop(pq)
                if in_tree[u]:
                    continue
                in_tree[u] = True
                total += w
                for v, wt in adj[u]:
                    if not in_tree[v]:
                        heapq.heappush(pq, (wt, v))
            return total

    Common mistakes

    • Adding an edge to a vertex already in the tree.
    • Assuming the graph is connected without checking.

    Similar problems