Skip to contentKEEP THE CRAFTTHE SANCTUARY

Measure a Minimum Spanning Tree

Find the weight of a minimum spanning tree with Kruskal's algorithm: sorted edges plus union-find.

The problem

Implement minimum_spanning_weight(node_count, edges). The nodes are labeled 0 to node_count - 1, with node_count >= 1, and each edge [u, v, weight] connects u and v in both directions. A spanning tree is a set of edges that connects every node without forming a cycle, and its weight is the sum of its edge weights. Return the smallest possible weight of a spanning tree, or -1 if the graph is not connected, so no spanning tree exists. Weights can be negative, and two nodes may be joined by more than one edge. For example, with 4 nodes and edges [[0, 1, 1], [1, 2, 2], [0, 2, 5], [2, 3, 1]] the answer is 4: keep the edges of weight 1, 1 and 2, and skip the edge of weight 5, which would close a cycle.

Starter code

def minimum_spanning_weight(node_count, edges):
    pass

Public examples

  1. node_count = 4, edges = [[0, 1, 1], [1, 2, 2], [0, 2, 5], [2, 3, 1]]gives4
  2. node_count = 4, edges = [[0, 1, 2], [2, 3, 3]]gives-1

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.