Skip to contentKEEP THE CRAFTTHE SANCTUARY

Kruskal's Minimum Spanning Tree

Connect every node with the lightest set of edges by taking edges from lightest to heaviest and skipping any edge that would close a cycle.

The problem

Kruskal's algorithm builds a minimum spanning tree: it looks at the edges from lightest to heaviest and keeps an edge only when it joins two parts of the graph that are not connected yet. Implement kruskal_edges(node_count, edges). The nodes are numbered 0 to node_count - 1, and each edge [u, v, weight] is undirected. Write every edge as [min(u, v), max(u, v), weight] and look at the edges in order of weight; when two edges have the same weight, the one with the smaller first node comes first, then the one with the smaller second node. Return the edges you keep, in the order you keep them. If the edges cannot connect all the nodes, return []. A graph with a single node needs no edges, so it also returns []. Example: with node_count = 4 and edges [[1, 0, 1], [1, 2, 2], [0, 2, 3], [3, 2, 1]], you keep [0, 1, 1], then [2, 3, 1], then [1, 2, 2]. The edge [0, 2, 3] is skipped because 0 and 2 are already connected.

Starter code

def kruskal_edges(node_count, edges):
    pass

Public examples

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

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

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