Lesson 27 · Problem-solving methods

Kruskal's Algorithm

Sort every edge by weight and take each one unless it closes a cycle. The whole algorithm is that sentence; union-find is what makes the cycle test fast.

Kruskal's Algorithm concept diagramTop: all nine edges of the six-vertex graph sorted by weight, E-F 1 through C-D 9. The first five are taken; after five edges the algorithm stops, since D-F, D-E, A-C and C-D would each close a cycle. Bottom: a merge tree of union-find components, where E-F, B-C, C-E, A-B and B-D each join two components until all six vertices form one tree of weight 15.1 · sort every edge, cheapest firstE-Fw 1takeB-Cw 2takeC-Ew 3takeA-Bw 4takeB-Dw 5takeD-Fw 6D-Ew 7A-Cw 8C-Dw 95 edges = V − 1: stop · each would close a cycle2 · each take is one unionE-F · 1B-C · 2C-E · 3A-B · 4B-D · 5one tree · weight 15EFBCADD-F would testfind(D) = find(F)same root: skip
1

Cheapest Edge First, Never a Cycle

  1. Sort every edge by weight, ascending.
  2. Take the next cheapest edge.
  3. Test whether its endpoints are already connected.
  4. Add it if they are not; discard it if they are.
  5. Stop at V−1 edges — the tree is complete.

Kruskal's algorithm finds a minimum spanning tree by considering edges in order of weight, cheapest first, and accepting each one unless it would create a cycle.

It is a greedy algorithm with an unusual property: it does not grow a connected tree. It builds a forest of separate components that gradually merge, and only at the final step does the forest become one tree.

The greedy choice is safe because of the cut property: for any partition of the vertices, the lightest edge crossing it belongs to some MST. When Kruskal accepts the lightest edge joining two components, that edge crosses the cut separating them, so it is safe.

  • A self-loop is always rejected: both ends are in the same set
  • Of several parallel edges, only the cheapest can ever be taken
  • Negative weights need no special care; only the order of weights matters
2

Why Union-Find Is Needed

Everything rests on one question asked once per edge: are these two vertices already connected?

Answering it with a graph traversal costs O(V) each time, making the algorithm O(E·V) — slower than the sort by a wide margin, and slow enough to be unusable on large graphs.

Disjoint sets answer it directly, which is why the Kruskal algorithm using disjoint set union is the standard way to write it. Each component is a set; find(u) == find(v) means an edge would close a cycle, and union(u, v) merges two components when an edge is accepted.

With path compression and union by rank, both operations run in inverse-Ackermann time — under 5 for any input that fits in a computer, so effectively constant. The cycle test stops being the bottleneck entirely.

  • find returns a component's representative (its root)
  • union links two roots, the shorter tree under the taller
  • Path compression points every visited vertex straight at its root
3

Complexity and When to Choose It

Sorting E edges costs O(E log E). The union-find operations add O(E·α(V)), which is effectively O(E). The sort dominates, so Kruskal is O(E log E).

Since E < V² in any simple graph, log E < 2 log V, and the bound is often written O(E log V) — the same thing.

Against Prim's algorithm at O(E log V) with a binary heap, the asymptotic difference is nil. The practical difference is structural: Kruskal needs the edge list sorted and touches the graph globally, while Prim grows outward from one vertex and needs adjacency access.

So Kruskal suits sparse graphs, where E is close to V and the sort is cheap, and is the natural choice when edges arrive as a list. Prim suits dense graphs, where E approaches V² and sorting them all is wasteful.

  • Sort once, then one find per endpoint and at most V−1 unions
  • Stop as soon as V−1 edges are taken; the rest of the list is never read
  • Edges already sorted: the cost drops to nearly O(E)
Implementation

Code in Python, C++ and Java

EDGES = [("A", "B", 4), ("A", "C", 8), ("B", "C", 2), ("B", "D", 5),
         ("C", "D", 9), ("C", "E", 3), ("D", "E", 7), ("D", "F", 6),
         ("E", "F", 1)]


class DisjointSet:
    def __init__(self, vertices):
        self.parent = {v: v for v in vertices}
        self.rank = {v: 0 for v in vertices}

    def find(self, v):
        while self.parent[v] != v:
            self.parent[v] = self.parent[self.parent[v]]   # path compression
            v = self.parent[v]
        return v

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False                                   # already connected
        if self.rank[ra] < self.rank[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        return True


def kruskal(vertices, edges):
    ds = DisjointSet(vertices)
    tree, total = [], 0

    for u, v, w in sorted(edges, key=lambda e: e[2]):
        if ds.union(u, v):
            tree.append((u, v, w))
            total += w
            print(f"  take   {u}-{v} ({w})   components merge")
        else:
            print(f"  skip   {u}-{v} ({w})   would close a cycle")

        if len(tree) == len(vertices) - 1:
            break

    return tree, total


def main():
    vertices = "ABCDEF"
    tree, total = kruskal(vertices, EDGES)
    print("\nMST edges ", " ".join(f"{u}-{v}" for u, v, _ in tree))
    print(f"total      {total}")


if __name__ == "__main__":
    main()
#include <algorithm>
#include <iostream>
#include <map>
#include <string>
#include <tuple>
#include <vector>
using Edge = std::tuple<std::string, std::string, int>;
class DisjointSet {
    public:
    explicit DisjointSet(const std::string& vertices) {
        for (char c : vertices) {
            const std::string v(1, c);
            parent_[v] = v;
            rank_[v] = 0;
        }
    }
    std::string find(std::string v) {
        while (parent_[v] != v) {
            parent_[v] = parent_[parent_[v]]; // path compression
            v = parent_[v];
        }
        return v;
    }
    bool unite(const std::string& a, const std::string& b) {
        std::string ra = find(a), rb = find(b);
        if (ra == rb) return false; // already connected
        if (rank_[ra] < rank_[rb]) std::swap(ra, rb);
        parent_[rb] = ra;
        if (rank_[ra] == rank_[rb]) ++rank_[ra];
        return true;
    }
    private:
    std::map<std::string, std::string> parent_;
    std::map<std::string, int> rank_;
};
int main() {
    const std::string vertices = "ABCDEF";
    std::vector<Edge> edges = {
    {
        "A", "B", 4
    }, {"A", "C", 8}, {"B", "C", 2}, {"B", "D", 5},
    {
        "C", "D", 9
    }, {"C", "E", 3}, {"D", "E", 7}, {"D", "F", 6},
    {
        "E", "F", 1
    }
    };
    std::sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b) {
    return std::get<2>(a) < std::get<2>(b);
    });
    DisjointSet ds(vertices);
    std::vector<Edge> tree;
    int total = 0;
    for (const auto& [u, v, w] : edges) {
        if (ds.unite(u, v)) {
            tree.emplace_back(u, v, w);
            total += w;
            std::cout << "  take   " << u << "-" << v << " (" << w
            << ")   components merge\n";
        } else {
            std::cout << "  skip   " << u << "-" << v << " (" << w
            << ")   would close a cycle\n";
        }
        if (tree.size() == vertices.size() - 1) break;
    }
    std::cout << "\nMST edges ";
    for (const auto& [u, v, w] : tree) std::cout << " " << u << "-" << v;
    std::cout << "\ntotal      " << total << "\n";
    return 0;
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
    static class DisjointSet {
        private final Map<String, String> parent = new HashMap<>();
        private final Map<String, Integer> rank = new HashMap<>();
        DisjointSet(String vertices) {
            for (char c : vertices.toCharArray()) {
                String v = String.valueOf(c);
                parent.put(v, v);
                rank.put(v, 0);
            }
        }
        String find(String v) {
            while (!parent.get(v).equals(v)) {
                parent.put(v, parent.get(parent.get(v))); // path compression
                v = parent.get(v);
            }
            return v;
        }
        boolean union(String a, String b) {
            String ra = find(a), rb = find(b);
            if (ra.equals(rb)) return false; // already connected
            if (rank.get(ra) < rank.get(rb)) {
                String t = ra;
                ra = rb;
                rb = t;
            }
            parent.put(rb, ra);
            if (rank.get(ra).equals(rank.get(rb))) rank.put(ra, rank.get(ra) + 1);
            return true;
        }
    }
    public static void main(String[] args) {
        String vertices = "ABCDEF";
        Object[][] edges = {
        {
            "A", "B", 4
        }, {"A", "C", 8}, {"B", "C", 2}, {"B", "D", 5},
        {
            "C", "D", 9
        }, {"C", "E", 3}, {"D", "E", 7}, {"D", "F", 6},
        {
            "E", "F", 1
        }
        };
        Arrays.sort(edges, (a, b) -> (Integer) a[2] - (Integer) b[2]);
        DisjointSet ds = new DisjointSet(vertices);
        List<String> tree = new ArrayList<>();
        int total = 0;
        for (Object[] e : edges) {
            String u = (String) e[0], v = (String) e[1];
            int w = (Integer) e[2];
            if (ds.union(u, v)) {
                tree.add(u + "-" + v);
                total += w;
                System.out.printf("  take   %s-%s (%d)   components merge%n", u, v, w);
            } else {
                System.out.printf("  skip   %s-%s (%d)   would close a cycle%n", u, v, w);
            }
            if (tree.size() == vertices.length() - 1) break;
        }
        System.out.printf("%nMST edges  %s%ntotal      %d%n", String.join(" ", tree), total);
    }
}
Watch it run

Step through it

Running on 6 vertices, 9 weighted edges, taken cheapest first

482593761ABCDEF
need5 edges to span 6 vertices
9 edges to choose from, 5 to keep
Step 1

the graph, and the goal

Six vertices, nine weighted edges. A spanning tree needs exactly five edges to connect everything; the minimum spanning tree is the cheapest such set.

Output
1 / 10
4

Edge Cases and Exam Traps

A disconnected graph has no spanning tree. The algorithm still runs to the end of the edge list and returns fewer than V−1 edges: one tree per component, a minimum spanning forest. Checking the edge count at the end tells you which case you are in.

Tied weights keep the total fixed but can change which edges are chosen. When two equal edges could each join the same pair of components, the sort order decides which one is taken, and both resulting trees are minimum. When every weight is different, the minimum spanning tree is unique.

A common exam slip is to reject an edge because one endpoint is already in the tree. That is Prim's test, not this one: an edge is rejected only when both endpoints are already in the same component.

  • Fewer than V−1 edges at the end means the graph was disconnected
  • Distinct weights: exactly one minimum spanning tree
  • Reject an edge only when both ends share a component