Algorithm · Graphs · O(E log E)

Kruskal’s minimum spanning tree

Sort the edges by weight and add each one unless it would close a cycle, checked with union-find: a minimum spanning tree in O(E log E).

The full derivation, edge cases and exercises are in the lesson Minimum spanning trees: cut and cycle properties, Kruskal and Prim. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

A minimum spanning tree connects every vertex of a weighted undirected graph with the least total weight. Kruskal’s algorithm is greedy: the lightest edge that does not create a cycle is always safe to add (the cut property).

Union-find answers “are these endpoints already connected?” in near-constant time, so the sort dominates. On a disconnected graph the result is a minimum spanning forest.

Steps

  1. Sort the edges by weight (ties by input order).
  2. For each edge, find the roots of both endpoints.
  3. Different roots: add the edge and union the two sets. Same root: skip it, it would close a cycle.
  4. Stop after V − 1 edges, or when the edges run out.

Invariants

What holds at every step; the correctness argument rests on these.

  • The chosen edges form a forest, and it is contained in some minimum spanning tree.
  • Two vertices share a union-find root exactly when the chosen edges connect them.

Complexity

Kruskal’s minimum spanning tree complexity
CaseTimeExtra spaceNotes
Whole algorithmO(E log E)O(V + E)Sorting dominates; the union-find work is O(E α(V)).

When to use it

Use it when

  • Cheapest network that connects every site: cabling, roads, clustering by cutting the heaviest tree edges.
  • Sparse graphs given as an edge list.

Avoid it when

  • The graph is directed (you need a minimum arborescence instead).
  • Dense graphs given as an adjacency matrix, where Prim’s algorithm is simpler.

Step through it

The interactive lab for kruskal’s minimum spanning tree: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

Kruskal in four languages (on top of the union-find lab’s UnionFind class), each checked against one shared fixture (accepted edges in order with the weight-then-index tie-break, total weight, components and edges examined before the early stop, including forests, ties and negative weights) and 500 random graphs compared with a brute-force search over every edge subset.

namespace Bekadan.Dsa.Examples.Graphs;
 
/// <summary>Accepted edge indices (in acceptance order), total weight, number of trees in the forest and edges examined.</summary>
public sealed record SpanningForest(List<int> Edges, long TotalWeight, int Components, int Examined);
 
/// <summary>
/// Kruskal's minimum spanning tree on an undirected graph (WeightedEdge lists each
/// edge once). Edges are scanned by (weight, input index); the UnionFind class
/// (union by rank, path compression) rejects an edge whose endpoints are already
/// connected, because it would close a cycle. Stops once n - 1 edges are chosen.
/// A disconnected graph yields a minimum spanning forest. O(E log E) for the sort,
/// O(E α(V)) for the union-find work. Negative weights are fine.
/// </summary>
public static class Kruskal
{
    public static SpanningForest Run(int nodeCount, IReadOnlyList<WeightedEdge> edges)
    {
        var sets = new UnionFind(nodeCount);
        var tree = new List<int>();
        long total = 0;
        int examined = 0;
 
        int[] order = Enumerable.Range(0, edges.Count).ToArray();
        Array.Sort(order, (a, b) => edges[a].Weight != edges[b].Weight ? edges[a].Weight.CompareTo(edges[b].Weight) : a.CompareTo(b));
 
        foreach (int i in order)
        {
            if (tree.Count == nodeCount - 1)
                break; // a spanning tree has exactly n - 1 edges
            var e = edges[i];
            examined++;
            int ru = sets.Find(e.From);
            int rv = sets.Find(e.To);
            if (ru == rv)
                continue; // already connected: this edge would close a cycle
            sets.Union(e.From, e.To);
            tree.Add(i);
            total += e.Weight;
        }
        return new SpanningForest(tree, total, sets.Count, examined);
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Graphs/Kruskal.cs

"""Kruskal's minimum spanning tree on an undirected graph (each edge listed once).
 
Edges are scanned by (weight, input index); UnionFind (union by rank, path
compression) rejects an edge whose endpoints are already connected, because it
would close a cycle. The scan stops once n - 1 edges are chosen. A disconnected
graph yields a minimum spanning forest. O(E log E) for the sort, O(E * alpha(V))
for the union-find work. Negative weights are fine.
"""
 
from dataclasses import dataclass
 
from dsa_examples.union_find import UnionFind
 
 
@dataclass
class SpanningForest:
    edges: list[int]  # accepted edge indices, in acceptance order
    total_weight: int
    components: int
    examined: int
 
 
def kruskal(node_count: int, edges: list[tuple[int, int, int]]) -> SpanningForest:
    sets = UnionFind(node_count)
    tree: list[int] = []
    total = 0
    examined = 0
 
    order = sorted(range(len(edges)), key=lambda i: (edges[i][2], i))
 
    for i in order:
        if len(tree) == node_count - 1:
            break  # a spanning tree has exactly n - 1 edges
        u, v, weight = edges[i]
        examined += 1
        ru, rv = sets.find(u), sets.find(v)
        if ru == rv:
            continue  # already connected: this edge would close a cycle
        sets.union(u, v)
        tree.append(i)
        total += weight
    return SpanningForest(tree, total, sets.count, examined)

Tested on CPython 3.14.0 · examples/python/dsa_examples/kruskal.py

package dev.bekadan.dsa.graphs;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
/**
 * Kruskal's minimum spanning tree on an undirected graph (each edge listed once). Edges are
 * scanned by (weight, input index); {@link UnionFind} (union by rank, path compression) rejects
 * an edge whose endpoints are already connected, because it would close a cycle. The scan stops
 * once n - 1 edges are chosen. A disconnected graph yields a minimum spanning forest.
 * O(E log E) for the sort, O(E α(V)) for the union-find work. Negative weights are fine.
 */
public final class Kruskal {
    private Kruskal() {
    }
 
    public record Edge(int from, int to, int weight) {
    }
 
    /** Accepted edge indices in acceptance order, total weight, trees in the forest, edges examined. */
    public record Result(List<Integer> edges, long totalWeight, int components, int examined) {
    }
 
    public static Result run(int nodeCount, List<Edge> edges) {
        UnionFind sets = new UnionFind(nodeCount);
        List<Integer> tree = new ArrayList<>();
        long total = 0;
        int examined = 0;
 
        Integer[] order = new Integer[edges.size()];
        Arrays.setAll(order, i -> i);
        Arrays.sort(order, (a, b) -> edges.get(a).weight() != edges.get(b).weight()
                ? Integer.compare(edges.get(a).weight(), edges.get(b).weight())
                : Integer.compare(a, b));
 
        for (int i : order) {
            if (tree.size() == nodeCount - 1) {
                break; // a spanning tree has exactly n - 1 edges
            }
            Edge e = edges.get(i);
            examined++;
            int ru = sets.find(e.from());
            int rv = sets.find(e.to());
            if (ru == rv) {
                continue; // already connected: this edge would close a cycle
            }
            sets.union(e.from(), e.to());
            tree.add(i);
            total += e.weight();
        }
        return new Result(tree, total, sets.count(), examined);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/graphs/Kruskal.java

#pragma once
 
#include <algorithm>
#include <cstddef>
#include <numeric>
#include <vector>
 
#include "bekadan/dsa/union_find.hpp"
 
namespace bekadan::dsa {
 
struct UndirectedEdge {
    std::size_t from;
    std::size_t to;
    int weight;
};
 
struct SpanningForest {
    std::vector<std::size_t> edges;  // accepted edge indices, in acceptance order
    long long total_weight = 0;
    std::size_t components = 0;
    std::size_t examined = 0;
};
 
// Kruskal's minimum spanning tree on an undirected graph (each edge listed once). Edges are
// scanned by (weight, input index); UnionFind (union by rank, path compression) rejects an edge
// whose endpoints are already connected, because it would close a cycle. The scan stops once
// n - 1 edges are chosen. A disconnected graph yields a minimum spanning forest.
// O(E log E) for the sort, O(E α(V)) for the union-find work. Negative weights are fine.
inline SpanningForest kruskal(std::size_t node_count, const std::vector<UndirectedEdge>& edges) {
    UnionFind sets(node_count);
    SpanningForest result;
 
    std::vector<std::size_t> order(edges.size());
    std::iota(order.begin(), order.end(), std::size_t{0});
    std::ranges::sort(order, [&edges](std::size_t a, std::size_t b) {
        return edges[a].weight != edges[b].weight ? edges[a].weight < edges[b].weight : a < b;
    });
 
    for (const std::size_t i : order) {
        if (result.edges.size() + 1 == node_count) break;  // a spanning tree has exactly n - 1 edges
        const UndirectedEdge& e = edges[i];
        ++result.examined;
        const std::size_t ru = sets.find(e.from);
        const std::size_t rv = sets.find(e.to);
        if (ru == rv) continue;  // already connected: this edge would close a cycle
        sets.unite(e.from, e.to);
        result.edges.push_back(i);
        result.total_weight += e.weight;
    }
    result.components = sets.count();
    return result;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/kruskal.hpp

Learn more

Data structures it uses

Problems, patterns and exercises

References