Implement Kruskal’s Algorithm

Pattern: Minimum spanning tree

medium

Kruskal's method sorts all edges by weight and takes each one whose two ends are not yet connected, checked with union-find. It stops being useful after n - 1 edges. This guide returns the chosen edges in the order taken.

The problem

Return the edges of a minimum spanning tree as [smaller end, larger end, weight], in the order Kruskal's method takes them. Weights are distinct, so the tree is unique. Vertices are numbered from 0 and each edge is [u, v, weight].

Think first

  • In what order are edges considered?
  • When is an edge skipped?
  • Which structure answers 'already connected?'

Hints

    Brute force, and why it fails

    Try every spanning tree: exponential.

    The key insight

    Taking the lightest edge that does not close a cycle is always safe, and union-find makes each check almost O(1).

    Dry run

    Take the 5-vertex example with edges 0-1 (2), 0-3 (6), 1-2 (3), 1-3 (8), 1-4 (5), 2-4 (7), 3-4 (9). Sorted: 2, 3, 5, 6, 7, 8, 9.

    Step 1 of 3

    The plan

    sort edges by weight
    for (u, v, w): if find(u) != find(v): union; take [min, max, w]
    

    Complexity

    Time
    O(E log E)
    Space
    O(V + E)

    Sorting dominates.

    Edge cases

    • A single vertex with no edges.
    • A graph in several pieces.
    • Two vertices joined by one edge.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<Integer>> kruskalMST(int n, int[][] edges) {
            int[][] sorted = edges.clone();
            Arrays.sort(sorted, (a, b) -> a[2] - b[2]);   // cheapest edges first
            int[] parent = new int[n];
            for (int i = 0; i < n; i++) parent[i] = i;
            List<List<Integer>> tree = new ArrayList<>();
            for (int[] e : sorted) {
                int a = find(parent, e[0]), b = find(parent, e[1]);
                if (a == b) continue;               // would make a cycle
                parent[a] = b;
                tree.add(Arrays.asList(Math.min(e[0], e[1]), Math.max(e[0], e[1]), e[2]));
            }
            return tree;
        }
    
        private int find(int[] parent, int x) {
            while (parent[x] != x) x = parent[x] = parent[parent[x]];
            return x;
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> kruskalMST(int n, vector<vector<int>>& edges) {
            vector<vector<int>> sorted(edges);
            sort(sorted.begin(), sorted.end(), [](const vector<int>& a, const vector<int>& b) { return a[2] < b[2]; });   // cheapest first
            vector<int> parent(n);
            for (int i = 0; i < n; i++) parent[i] = i;
            vector<vector<int>> tree;
            for (const vector<int>& e : sorted) {
                int a = find(parent, e[0]), b = find(parent, e[1]);
                if (a == b) continue;               // would make a cycle
                parent[a] = b;
                tree.push_back(vector<int>{min(e[0], e[1]), max(e[0], e[1]), e[2]});
            }
            return tree;
        }
    
        int find(vector<int>& parent, int x) {
            while (parent[x] != x) x = parent[x] = parent[parent[x]];
            return x;
        }
    };

    Python

    class Solution:
        def kruskalMST(self, n: int, edges: list[list[int]]) -> list[list[int]]:
            parent = list(range(n))
    
            def find(x):
                while parent[x] != x:
                    parent[x] = parent[parent[x]]
                    x = parent[x]
                return x
    
            tree = []
            for u, v, w in sorted(edges, key=lambda e: e[2]):   # cheapest edges first
                a, b = find(u), find(v)
                if a != b:                          # skip edges that would make a cycle
                    parent[a] = b
                    tree.append([min(u, v), max(u, v), w])
            return tree

    Common mistakes

    • Forgetting to sort.
    • Checking only whether the ends have been seen, not whether they are connected.

    Similar problems