Kruskal's MST Weight

Step 2: Kruskal's MST Weight

Kruskal's algorithm builds the MST greedily: sort every edge by weight, then walk through them cheapest-first, adding an edge only when it links two currently separate components (using the DSU from Step 1). Skipping edges that would form a cycle guarantees the minimum total cost.

Implement kruskal(n, edges):

  • n is the number of nodes (0..n-1).
  • edges is a list of (u, v, weight) tuples for an undirected graph.
  • Return the total weight of the MST.

Real use: this total is the minimum cabling budget needed to connect the whole network.

Hints
Starter code
class DSU:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

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

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        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 connected(self, a, b):
        return self.find(a) == self.find(b)


def kruskal(n, edges):
    """Return the total weight of the MST using Kruskal's algorithm."""
    # TODO: sort edges by weight, union non-cyclic ones, sum their weights
    pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.