Algo-Sim › Advanced Graphs

Minimum Spanning Tree (Kruskal)

Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input

Connect all nodes with the cheapest set of edges. Kruskal: sort edges by weight and take each one whose ends Union-Find says are not yet connected.

Problem

Given a connected undirected graph with nodes 0..n − 1 and weighted edges, return the total weight of a minimum spanning tree: a set of n − 1 edges that connects every node at the smallest possible total weight. This version uses Kruskal's algorithm.

Constraints

Edge cases to test

Follow-up questions

Kruskal or Prim?
Kruskal is O(E log E) and simple on sparse edge lists; Prim with an array is O(V²), better for dense graphs.
How do you find a second-best MST?
For each non-tree edge, swap it with the heaviest edge on the tree path between its ends, and take the cheapest swap.

Solution

Java

public int minimumSpanningTree(int n, int[][] edges) {
    Arrays.sort(edges, (a, b) -> Integer.compare(a[2], b[2]));
    int[] parent = new int[n];
    for (int i = 0; i < n; i++) parent[i] = i;
    int total = 0, used = 0;
    for (int[] e : edges) {
        int a = find(parent, e[0]), b = find(parent, e[1]);
        if (a == b) continue;
        parent[a] = b;
        total += e[2];
        used++;
        if (used == n - 1) break;
    }
    return used == n - 1 ? total : -1;
}

private int find(int[] parent, int x) {
    while (parent[x] != x) {
        parent[x] = parent[parent[x]];
        x = parent[x];
    }
    return x;
}

Python

def minimum_spanning_tree(n, edges):
    edges = sorted(edges, key=lambda e: e[2])
    parent = list(range(n))

    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x

    total = used = 0
    for u, v, w in edges:
        a, b = find(u), find(v)
        if a == b:
            continue
        parent[a] = b
        total += w
        used += 1
        if used == n - 1:
            break
    return total if used == n - 1 else -1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int minimumSpanningTree(int n, vector<vector<int>> &edges) {
        sort(edges.begin(), edges.end(), [](const auto &a, const auto &b) { return a[2] < b[2]; });
        vector<int> parent = vector<int>(n);
        for (int i = 0; i < n; i++)
            parent[i] = i;
        int total = 0, used = 0;
        for (vector<int> &e : edges) {
            int a = find(parent, e[0]), b = find(parent, e[1]);
            if (a == b)
                continue;
            parent[a] = b;
            total += e[2];
            used++;
            if (used == n - 1)
                break;
        }
        return used == n - 1 ? total : -1;
    }

    int find(vector<int> &parent, int x) {
        while (parent[x] != x) {
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }
};

More Advanced Graphs problems