Kruskal's Algorithm: Building Minimum Spanning Trees

Learn Kruskal's algorithm for finding minimum spanning trees in weighted graphs using union-find data structures.

published: reading time: 18 min read author: Geek Workbench updated: May 17, 2026
Quick Summary

Kruskal's algorithm builds a minimum spanning tree for a connected, undirected weighted graph by sorting edges and using union-find to skip cycles. On disconnected input, it returns a minimum spanning forest. This guide covers the cut property, negative and tied weights, Python's arbitrary-precision total, and how Kruskal's sorting cost compares with heap-based and dense-graph versions of Prim's algorithm.

Kruskal’s Algorithm: Building Minimum Spanning Trees

An MST connects every vertex in a connected, undirected weighted graph with the least possible total edge weight and no cycles. Kruskal’s algorithm sorts the edges, then uses union-find to accept an edge only when it joins two different components. If the graph is disconnected, the same process returns a minimum spanning forest: one tree for each connected component.

Introduction

The input must be an undirected graph with a weight on each edge. A connected graph has an MST with V - 1 edges; a disconnected graph has no single spanning tree, so Kruskal returns a minimum spanning forest instead. This article walks through union-find, the cut-property argument, and the trade-offs with Prim’s algorithm.

The Union-Find Data Structure

Kruskal uses union-find to check whether an edge would create a cycle:

class UnionFind:
    """Union-Find (Disjoint Set Union) with path compression and union by rank."""

    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

    def find(self, x):
        """Find root with path compression."""
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])  # Compress path
        return self.parent[x]

    def union(self, x, y):
        """Union by rank. Returns True if merged, False if already connected."""
        root_x, root_y = self.find(x), self.find(y)

        if root_x == root_y:
            return False  # Already in same set = would create cycle

        # Union by rank: attach smaller tree under larger
        if self.rank[root_x] < self.rank[root_y]:
            root_x, root_y = root_y, root_x

        self.parent[root_y] = root_x
        if self.rank[root_x] == self.rank[root_y]:
            self.rank[root_x] += 1

        return True

Kruskal’s Algorithm

def kruskal_mst(num_vertices, edges):
    """
    Kruskal's algorithm for an MST or minimum spanning forest.

    Args:
        num_vertices: Number of vertices
        edges: List of (weight, u, v) tuples

    Returns:
        A list of (weight, u, v) edges and their total weight. For a connected
        graph the list is an MST; otherwise it is a minimum spanning forest.
    """
    # Sort edges by weight
    sorted_edges = sorted(edges, key=lambda x: x[0])

    uf = UnionFind(num_vertices)
    mst_edges = []
    total_weight = 0

    for weight, u, v in sorted_edges:
        if uf.union(u, v):  # If union succeeded (no cycle formed)
            mst_edges.append((weight, u, v))
            total_weight += weight

            # A connected graph's MST has exactly V-1 edges.
            if len(mst_edges) == num_vertices - 1:
                break

    return mst_edges, total_weight

total_weight is safe for large positive or negative Python integers because Python integers have arbitrary precision. If you port this code to a fixed-width integer type, use a sufficiently wide accumulator or checked arithmetic.

Small correctness checks

Equal-weight edges can produce different trees with the same minimum total. Negative weights are valid, and disconnected input returns a forest rather than an empty result.

# Equal weights: either two-edge tree has the minimum total of 2.
edges_with_tie = [(1, 0, 1), (1, 1, 2), (2, 0, 2)]
tie_tree, tie_total = kruskal_mst(3, edges_with_tie)
assert len(tie_tree) == 2
assert tie_total == 2

# Negative weights are sorted and included when they connect components.
negative_edges = [(-3, 0, 1), (-1, 1, 2), (4, 0, 2)]
negative_tree, negative_total = kruskal_mst(3, negative_edges)
assert len(negative_tree) == 2
assert negative_total == -4

# Two disconnected components produce two trees in the forest.
disconnected_edges = [(1, 0, 1), (2, 2, 3)]
forest, forest_total = kruskal_mst(4, disconnected_edges)
assert len(forest) == 2
assert forest_total == 3

When to Use Kruskal’s Algorithm

Kruskal and Prim both find an MST for a connected undirected weighted graph. On disconnected input, Kruskal returns a forest; Prim can be run from each unvisited component.

Kruskal is a good fit when:

  • You need a Minimum Spanning Tree
  • The input is already an edge list or the graph is sparse
  • You want a simple, easy-to-implement solution
  • Graph may be disconnected (produces forest)

Consider another approach when:

  • You need single-source shortest paths (use Dijkstra)
  • The graph is dense and Prim’s adjacency-matrix implementation may be a better fit
  • You need to preserve existing spanning tree structure

Trade-off Analysis

Method Typical time Representation Notes
Kruskal O(E log E) for sorting, plus O(E α(V)) union-find work Edge list Often convenient for sparse graphs or when edges are already listed. It returns a forest on disconnected input.
Prim with a binary heap O((V + E) log V) Adjacency list Often a good fit for sparse connected graphs; details depend on the heap and graph representation.
Prim with an adjacency matrix O(V²) Adjacency matrix Can be competitive on dense graphs where E is close to V².

There is no universal winner. Compare graph density, input format, memory limits, and the implementation on your workload.

Production Failure Scenarios

  1. Disconnected graph: Kruskal returns a forest. Check whether it has V - 1 edges when the caller requires one spanning tree.
  2. Total-weight range: Python integers do not overflow at a fixed width. In languages with fixed-width integers, use a wide enough type or checked addition for the sum.
  3. Large edge list: Sorting dominates Kruskal’s running time. For dense graphs, compare it with Prim’s O(V²) adjacency-matrix implementation.

Complete Example

def solve():
    # Example: Network connection problem
    # n = number of servers, connections = [(city1, city2, cost)]

    n = 4
    connections = [
        (1, 2, 1),   # (u, v, cost)
        (2, 3, 2),
        (3, 4, 3),
        (4, 1, 4),
        (1, 3, 10)
    ]

    # Convert to (cost, u, v) format for Kruskal's
    edges = [(cost, u-1, v-1) for u, v, cost in connections]

    mst, total = kruskal_mst(n, edges)

    if len(mst) == n - 1:
        print(f"MST weight: {total}")
        print("Edges:", [(u+1, v+1, w) for w, u, v in mst])
    else:
        print(f"Minimum spanning forest weight: {total}")
        print("Forest edges:", [(u+1, v+1, w) for w, u, v in mst])

Quick Recap Checklist

  • Sort all edges by weight
  • Use union-find to detect cycles
  • Add edge if it connects two different components
  • Stop after V-1 edges when the graph is connected
  • For disconnected graphs, produces a forest
  • Total weight is minimized

Interview Questions

1. Why does Kruskal's algorithm produce a minimum spanning tree?

Kruskal's relies on the cut property: for a cut that respects the edges already chosen, a lightest edge crossing that cut is safe to add and belongs to some MST. If several crossing edges tie, any of them may be safe. Union-find skips edges whose endpoints are already connected. In a connected graph this process ends with V-1 edges; in a disconnected graph it ends with a minimum spanning forest.

2. What's the difference between Kruskal's and Prim's algorithms?

Both build spanning trees greedily on connected input, but they choose edges differently. Kruskal's looks at all edges globally, sorts them, and adds the cheapest edge that doesn't create a cycle. Prim's grows a tree from a starting vertex, always adding the cheapest edge from the tree to an outside vertex. Kruskal's is easier to implement with union-find; Prim's is often faster for dense graphs with adjacency matrix representation.

3. How does union-find detect cycles in Kruskal's?

Union-find maintains connected components. Before adding an edge (u, v), we check if u and v are already in the same component using find(). If they share a root, they're already connected through some path—adding this edge would create a cycle. If they're in different components, union() merges them and we safely add the edge. Path compression and union by rank make this O(α(V)) amortized per operation.

4. Can Kruskal's handle a graph with negative edge weights?

Yes. Kruskal's algorithm works with negative edge weights because it simply sorts edges by weight and adds them if they don't form a cycle. Negative weights don't violate the cut property that guarantees correctness. Python's int type has arbitrary precision, so this implementation's total does not overflow at a fixed width. A fixed-width port needs a wide enough accumulator or checked addition.

5. What is the time complexity of Kruskal's algorithm and what factors influence it?

Sorting E edges takes O(E log E). Union-find adds O(E α(V)) amortized work with path compression and union by rank, where α is the inverse Ackermann function. For sparse graphs, heap-based Prim runs in O((V + E) log V). For dense graphs with E near V², Prim with an adjacency matrix runs in O(V²). The better choice depends on graph representation and workload.

6. How would you modify Kruskal's algorithm to find a maximum spanning tree?

Two equivalent approaches:

  • Negate weights: Multiply all edge weights by -1 and run standard Kruskal's (minimum on negated weights = maximum on original).
  • Reverse sort: Sort edges in descending order instead of ascending, then apply the same cycle-detection logic.

Both produce a Maximum Spanning Tree (MaxST) with the same O(E log E) complexity. The correctness follows from the same cut property, but applied to the complement: the heaviest edge crossing any cut belongs to some maximum spanning tree.

7. Does Kruskal's algorithm work correctly on graphs with zero-weight edges?

Yes. Zero-weight edges are handled exactly like any other edge. They are sorted by weight and added if they don't create a cycle. The only subtlety arises when multiple MSTs exist — zero-weight edges can create ties. In such cases, Kruskal's may produce any valid MST depending on the tie-breaking order. The total weight will still be minimal, though there may be multiple optimal spanning trees with the same total weight.

8. What real-world applications use Kruskal's algorithm and MSTs?

Common uses include:

  • Network design: Laying fiber-optic cables, electrical grids, or water pipelines at minimum cost while connecting all nodes
  • Cluster analysis: Single-linkage clustering uses an MST — cutting the heaviest edges produces clusters
  • Image segmentation: Treating pixels as graph nodes and edge weights as dissimilarity, MST-based segmentation isolates regions
  • Approximation algorithms: The 2-approximation for the Traveling Salesman Problem uses an MST as a backbone
  • Circuit design: Minimizing wire length connecting components on a printed circuit board
9. What is the cut property and why is it fundamental to Kruskal's correctness?

For a cut that respects the edges already selected, a minimum-weight crossing edge is safe to add; if there is a tie, each tied minimum edge belongs to some MST. This cut-property argument justifies Kruskal's greedy choice.

At each step, the chosen edges form a forest. Consider a cut that separates two of its components. The lightest edge crossing that cut can connect them without making a cycle, and the cut property says there is an MST containing that edge. If multiple edges tie for the minimum, each is a valid choice for some MST.

10. How does path compression improve union-find performance?

Path compression flattens the tree during find() by making nodes along the search path point directly to the root. A later lookup from those nodes takes O(1) time instead of traversing the same path again.

Combined with union by rank (attaching shorter trees under taller ones), operations take O(α(V)) amortized time, where α is the inverse Ackermann function. It grows so slowly that it is effectively constant for input sizes seen in practice. Sorting therefore dominates Kruskal's running time for most inputs.

11. What happens when Kruskal's encounters equal-weight edges?

Equal-weight edges can be processed in any order without affecting the total weight of the minimum spanning tree or forest. The specific tree structure may differ depending on which tied edge is chosen first.

The order used to break ties determines which tree is returned. To make the result deterministic, sort by weight and then by an edge identifier or endpoint indices. Ties can allow multiple MSTs with the same total weight, though a graph may still have a unique MST.

12. Why is union by rank used instead of simple union or union by size?

Union by rank attaches the shorter tree under the root of the taller tree. The "rank" approximates tree height without storing extra data. This keeps trees roughly balanced and avoids the O(V)-height trees that naive union can create by attaching roots without balancing.

Union by size tracks the number of nodes in each component and achieves similar balance. Both rank and size support the standard O(α(V)) amortized bound when paired with path compression; implementations can use either.

13. How would you parallelize Kruskal's algorithm for large-scale graphs?

Parallelizing Kruskal's has two main bottlenecks:

  • Sorting: Use parallel sort (e.g., GPU sort, multi-core merge sort) for the O(E log E) edge sorting phase
  • Union-find: The cycle checks are inherently sequential due to component merges—only independent edges (connecting different components) can be processed in parallel

A common approach: sort edges in parallel, then partition independent edges into batches that can be processed concurrently using a parallel union-find variant or a lock-free approach. Borůvka's algorithm (which performs parallel "contraction" steps) is often easier to parallelize and is frequently combined with Kruskal's in modern MST implementations.

14. What is the inverse Ackermann function and why does it appear in union-find analysis?

The inverse Ackermann function α(V) grows so slowly that it is effectively constant for input sizes seen in practice.

It appears in the amortized analysis of union-find with path compression and union by rank: each find or union takes O(α(V)) amortized time. In Kruskal's O(E log E + E·α(V)) bound, the sorting term usually dominates.

15. Can Kruskal's algorithm be adapted to find non-minimum spanning trees?

Yes, with simple modifications:

  • Maximum Spanning Tree: Sort edges in descending order (or negate weights), keeping the greedy strategy but always picking the heaviest non-cycling edge. Correctness follows from the same cut property applied to the maximum.
  • K-th Minimum Spanning Tree: Use a modified approach with edge deletions and reconnections (Eppstein's algorithm finds the K-th MST in O(E + V log V + K log V))
  • Second-best MST: Find the MST normally, then for each non-MST edge, compute the minimum weight increase when substituting it for an edge in the MST cycle it creates

The core greedy structure remains, but changing the selection criterion (heaviest instead of lightest, or constrained substitutions) extends Kruskal's beyond pure minimization.

16. How does Kruskal's compare when using a binary heap versus full sorting?

Both approaches have O(E log E) worst-case time, with different costs in practice:

  • Full sorting (standard): Sorts all E edges upfront with efficient comparison sorts. One-time O(E log E) cost, no per-operation overhead.
  • Binary heap: Insert all edges into heap O(E), then repeatedly extract-min O(log E) × O(E). Total O(E log E), but with larger constant factors from heap operations. Useful when edges are generated incrementally.
  • Fibonacci heap: The O(E + V log V) bound applies to Prim's algorithm, where decrease-key operations matter; it is not a faster sorting bound for Kruskal.

For Kruskal, full sorting is usually simpler and often faster in practice. Prim's algorithm benefits more from a heap because it updates candidate edges as the tree grows.

17. What edge cases must be handled when implementing Kruskal's algorithm?

Critical edge cases include:

  • Disconnected graph: The result is a forest. Check that len(mst_edges) == V - 1 if the caller requires one MST.
  • Self-loops: An edge from a vertex to itself is skipped because both endpoints are already in the same component.
  • Parallel edges: Multiple edges between the same two vertices: all are valid candidates; the lightest that connects two components is added. Subsequent parallel edges between already-connected vertices are rejected.
  • Total weight: Python integers have arbitrary precision. In a fixed-width language, use a sufficiently wide or checked accumulator.
  • Empty graph or single vertex: Handle these according to the caller's convention; the empty edge set has total 0 in this implementation.
18. How does Kruskal's handle parallel edges between the same pair of vertices?

Parallel edges (multiple edges with the same endpoints but possibly different weights) are handled naturally by the algorithm. All parallel edges are sorted together by weight. The first one that connects two different components is added; the others are skipped because they would create cycles.

With three A-B edges of weights 5, 10, and 15, Kruskal considers the weight-5 edge first. If it joins two components, the heavier parallel edges are later skipped because A and B are already connected. If a lighter path has already connected A and B, all three edges are skipped as cycle-forming edges.

19. What is the difference between MST and Minimum Spanning Forest?

A Minimum Spanning Tree (MST) is defined for a connected graph—it spans all vertices with minimum total weight. A Minimum Spanning Forest (MSF) is the generalization for disconnected graphs: one MST per connected component.

Kruskal's naturally produces a Minimum Spanning Forest because it processes all edges globally. When two components cannot be connected (no edge crosses the remaining cuts between them), they remain separate trees in the forest. Kruskal detects disconnectedness as it processes the edge list and returns the trees it can form without a separate connectivity check.

20. How would you find the second-best MST using Kruskal's as a base?

To find the second-best MST (the spanning tree with the second-lowest total weight):

  1. Run Kruskal's to find the MST with total weight W₁
  2. For each non-MST edge e with weight w_e, identify the unique path in the MST between its endpoints. Find the maximum-weight edge f on that path such that w_e > w_f
  3. Replacing f with e gives a spanning tree with weight W₁ - w_f + w_e
  4. The minimum across all candidates is the second-best MST

Using LCA (Lowest Common Ancestor) with binary lifting, step 2 can be answered in O(log V) per edge, making total O(E log V). This works because any spanning tree differing from the MST must replace exactly one edge—the "minimum maximum-weight edge" criterion ensures we make the smallest possible increase.

Further Reading

To deepen your understanding of Kruskal’s algorithm and related topics, explore these resources:

  • Prim’s Algorithm: Growing a Minimum Spanning Tree — The complementary MST algorithm; compare how Prim’s grows a single tree vs. Kruskal’s global edge sorting approach
  • Union-Find (Disjoint Set Union) Deep Dive — Master the data structure that makes Kruskal’s cycle detection efficient with path compression and union by rank
  • The Cut Property and Cycle Property — These two theorems form the theoretical foundation for all MST algorithms. Understanding them explains why greedy MST algorithms are correct
  • Borůvka’s Algorithm — The earliest MST algorithm (1926), rediscovered for parallel and distributed computing contexts
  • Minimum Spanning Tree Applications — Explore real-world uses: network design, cluster analysis, image segmentation, approximation algorithms (traveling salesman problem), and circuit design
  • Cormen et al., Introduction to Algorithms (CLRS) — Chapters on MST algorithms with formal proofs and complexity analysis

Kruskal processes edges from lightest to heaviest, adding an edge when it joins two components. The cut property explains why that choice preserves an optimal result.

Conclusion

Kruskal’s algorithm builds a minimum spanning tree by sorting all edges and adding them one by one, skipping any that would create a cycle. Union-find makes cycle detection nearly O(1) amortized. It’s particularly clean for sparse graphs and naturally produces a forest when the input is disconnected. If your graph is dense, Prim’s algorithm with an adjacency matrix may be faster. To compare them directly, see Prim’s Algorithm: Growing a Minimum Spanning Tree.

Category

Related Posts

Prim's Algorithm: Growing a Minimum Spanning Tree

Learn Prim's algorithm for finding minimum spanning trees starting from a vertex, using a greedy approach with priority queues.

#prim #mst #minimum-spanning-tree

Bellman-Ford Algorithm: Shortest Paths with Negative Weights

Learn the Bellman-Ford algorithm for single-source shortest paths including negative edge weights and negative cycle detection.

#bellman-ford #shortest-path #graph-algorithms

Dijkstra's Algorithm: Finding Shortest Paths in Weighted Graphs

Learn Dijkstra's algorithm for single-source shortest paths in graphs with non-negative edge weights, including implementations and trade-offs.

#dijkstra #shortest-path #graph-algorithms