Minimum Spanning Trees

Connect every vertex at minimum total cost — Kruskal's and Prim's algorithms and the cut property behind them.

Intermediate 2 min readLesson 13 of 18 Interview Q&A

Given a connected, weighted, undirected graph, a spanning tree connects all V vertices with exactly V − 1 edges and no cycles. A minimum spanning tree (MST) is one whose total edge weight is smallest. Think: lay cable to connect every building as cheaply as possible.

4215837ABCDE
MST (highlighted): B–C 1, A–C 2, D–E 3, B–D 5 → total 11.

The cut property

Split the vertices into any two groups. The cheapest edge crossing the split belongs to some MST. Both classic algorithms are just different ways of repeatedly applying this greedy rule.

Kruskal's algorithm

Sort all edges by weight. Add each edge unless it would create a cycle — which Union-Find detects in near-O(1). Stop at V − 1 edges.

int kruskal(int n, int[][] edges) {                    // edges: {u, v, w}
    Arrays.sort(edges, (a, b) -> Integer.compare(a[2], b[2]));
    DSU dsu = new DSU(n);
    int total = 0, used = 0;
    for (int[] e : edges) {
        if (dsu.union(e[0], e[1])) {                   // false → would form a cycle
            total += e[2];
            if (++used == n - 1) break;
        }
    }
    return used == n - 1 ? total : -1;                 // -1: graph not connected
}

Time: O(E log E) for sorting — dominated by the sort.

Prim's algorithm

Grow a single tree from a start vertex. Repeatedly add the cheapest edge leaving the tree, using a min-heap — structurally almost identical to Dijkstra, but the key is the edge weight, not the path distance.

int prim(List<List<int[]>> adj) {                     // adj[u] = {v, w}
    int n = adj.size(), total = 0;
    boolean[] inTree = new boolean[n];
    PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
    pq.offer(new int[]{0, 0});
    while (!pq.isEmpty()) {
        int[] top = pq.poll();
        int u = top[0];
        if (inTree[u]) continue;
        inTree[u] = true;
        total += top[1];
        for (int[] e : adj.get(u)) if (!inTree[e[0]]) pq.offer(new int[]{e[0], e[1]});
    }
    return total;
}

Time: O(E log V) with a binary heap.

Kruskal
  • Edge-centric: sort edges, add if no cycle
  • Needs Union-Find
  • Great for sparse graphs or an edge list
  • Naturally handles forests (disconnected graphs)
Prim
  • Vertex-centric: grow one tree
  • Needs a priority queue
  • Great for dense graphs (O(V²) with an array)
  • Similar code to Dijkstra

Applications: network and circuit design, clustering (remove the k−1 heaviest MST edges to get k clusters), approximation for the travelling salesman problem (2× optimal for metric TSP), image segmentation.

Key takeaways
  • An MST connects all vertices with minimum total weight using V − 1 edges.
  • The cut property justifies greedy choices.
  • Kruskal: sort edges + Union-Find, O(E log E). Prim: heap from a start vertex, O(E log V).
  • If all edge weights are distinct, the MST is unique.
Interview questions
QMin cost to connect all points (Manhattan distance).medium

It's a complete graph with V² edges. Prim's with an O(V²) array (no heap) is ideal for dense graphs: keep minDist[v] to the tree and pick the smallest each round.

QIs the shortest-path tree from Dijkstra the same as the MST?medium

No. Dijkstra minimises each vertex's distance from one source; the MST minimises the total weight of the tree. A triangle with edges A–B 2, B–C 2, A–C 3: from A, the shortest-path tree uses A–C (3), but the MST uses A–B and B–C (total 4 vs 5).