Graphs · Pattern 13 of 14

Minimum spanning tree: Kruskal's algorithm

Sort the edges by cost and add each one unless it would close a loop (union-find tells you). After n − 1 edges every node is connected as cheaply as possible.

1 variation · 2 problems · 1 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Connect every city, house or point at the lowest total cost
  • Any connected result is fine; only the total cost matters

The template

Minimum Spanning Tree
// Kruskal: cheapest edges first, skip any edge that would close a loop. Cities are 1..n.
int minimumCost(int n, int[][] connections) {
    int[] parent = new int[n + 1];
    for (int i = 0; i <= n; i++) parent[i] = i;
    Arrays.sort(connections, (a, b) -> Integer.compare(a[2], b[2]));
    int total = 0, used = 0;
    for (int[] e : connections) {
        int ra = find(parent, e[0]), rb = find(parent, e[1]);
        if (ra == rb) continue;                   // already connected: this edge is a loop
        parent[ra] = rb;
        total += e[2];
        used++;
    }
    return used == n - 1 ? total : -1;            // fewer edges: the graph is not connected
}
int find(int[] parent, int x) {
    while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; }
    return x;
}

The variations

  1. 1Kruskal with union-find

    Sort edges by cost and keep each one that joins two different components. With dense graphs (every pair of points), Prim's algorithm with a heap or an O(n²) scan does the same job.

Mistakes to avoid

  • Forgetting to check that n − 1 edges were used: if not, some city can never be reached and the answer is −1.
  • Using Dijkstra here. Dijkstra minimises the path from one source; an MST minimises the total cost of all edges.
Next: Degree counting: answers without a search →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.