Skip to content
DeepForgeby svx
All problems
MediumGraph Algorithmsgraph-025

Kruskal MST Weight

Problem

Compute the total weight of a minimum spanning tree using Kruskal's algorithm with union-find.

edges is a list of [u, v, w] triples describing an undirected weighted graph. Return -1 when the graph is disconnected and 0 for a single node.

Hint

Sort by weight and take any edge that joins two different components.

Test cases

case 1
in: [4,[[0,1,1],[1,2,2],[2,3,3],[0,3,10]]]
expected: 6
case 2
in: [4,[[0,1,1],[1,2,2]]]
expected: -1
case 3
in: [1,[]]
expected: 0
case 4
in: [3,[[0,1,3],[1,2,2],[0,2,1]]]
expected: 3
Starter codePython
def kruskal_mst_weight(n, edges):
    # Your code here
    pass

4 test cases · run your code against them in the editor