Kruskal Builds Minimum Spanning Trees
Sort edges by weight, union the endpoints when their roots differ, and stop after n-1 picks: the result is a minimum spanning tree with cycle rejection.
Code
def find(parent, node: int) -> int:
while parent[node] != node:
parent[node] = parent[parent[node]] # halve the path
node = parent[node]
return node
def kruskal(nodes: int, edges: list[tuple[int, int, int]]) -> tuple[int, list]:
parent = list(range(nodes))
total = 0
picked: list[tuple[int, int, int]] = []
# Edges are (weight, a, b) so plain tuple order sorts by weight
for weight, a, b in sorted(edges):
root_a, root_b = find(parent, a), find(parent, b)
if root_a == root_b:
continue # this edge would close a cycle
parent[root_a] = root_b
total += weight
picked.append((weight, a, b))
if len(picked) == nodes - 1:
break
return total, picked
edges = [
(4, 0, 1),
(3, 0, 2),
(1, 1, 2),
(2, 1, 3),
(5, 2, 3),
]
total, picked = kruskal(4, edges)
print(f"mst weight: {total}")
for edge in picked:
print("edge", edge)Output
Captured from a sandboxed run of this snippet in the build pipeline.
mst weight: 6
edge (1, 1, 2)
edge (2, 1, 3)
edge (3, 0, 2)The anatomy of the snippet
Structurally, expect the functions find and kruskal and nothing else.
A single loop drives the file — while parent[node] != node.
Points of care
- Installation is a non-issue here; everything stays within the standard library.
Applying it
The callable that organises the rest: def find(parent, node: int) -> int
The file’s steps show up in the output as mst weight:, edge.
Treat find as the API: import it, and ignore the supporting code.
Statements that matter
def find(parent, node: int) -> int:
while parent[node] != node:
parent[node] = parent[parent[node]] # halve the path
node = parent[node]
return node
Interactive Tools for This Topic
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `find`, `kruskal` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.