Video in progress

Strong Middle 🧠 Problem solving

What is a minimum spanning tree? How do Kruskal's and Prim's algorithms differ, and when do you pick which?

An MST is the set of edges that connects all nodes without creating a cycle and has the smallest total weight. Kruskal sorts the edges by weight and checks for cycles with Union-Find: O(E log E). Prim grows from one node and takes the cheapest outgoing edge from a heap: O(E log V). Kruskal suits sparse graphs, Prim dense ones.

📖 Answer

An example: you need to connect districts with fiber optic cable, and the cost between each pair is known. Everything must be connected and the total cost must be minimal.

record Edge(int u, int v, int w) {}

static long kruskal(int n, List<Edge> edges) {
    List<Edge> sorted = new ArrayList<>(edges);
    sorted.sort(Comparator.comparingInt(Edge::w));
    Dsu dsu = new Dsu(n);                 // plain Union-Find: find + union
    long total = 0;
    int used = 0;
    for (Edge e : sorted) {
        if (dsu.union(e.u(), e.v())) {    // false — this edge would form a cycle
            total += e.w();
            if (++used == n - 1) break;
        }
    }
    return used == n - 1 ? total : -1;    // -1 — the graph is disconnected
}

Prim is very similar to Dijkstra, with a difference in one place: what goes into the heap is the edge's own weight, not the distance from the source. You skip stale entries "lazily" in the same way.

Both are greedy and both are correct because of the "cut property": if you split the graph into any two parts, the cheapest edge between them is in some MST.

How I choose:

  • the edge list is ready and the graph is sparse: Kruskal, with short code;
  • the graph is dense or in adjacency list form: Prim;
  • a complete graph with V in the low thousands: array-based Prim at O(V²), with no heap, is the fastest.

A frequently asked question: does an MST give the shortest path between two cities? No. An MST minimizes the total cost, and an individual path within it can be much longer. That's Dijkstra's job.