Connect components, skip the cycles.
Sort edges globally and use DSU to accept only safe component merges.
01 Model the idea
Kruskal’s algorithm considers edges from cheapest to most expensive, accepting an edge only if it joins two different components. Disjoint-set union makes that cycle test efficient. The accepted edges form a forest throughout the process. For a connected graph, exactly V−1 accepted edges produce a spanning tree; disconnected input yields only a forest unless the contract rejects it.
The accepted edge set is always a forest.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
SORT edges by increasing cost
ACCEPT only edges whose endpoints have different representatives
UNION those components03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
def kruskal(n, edges):
parent, size = list(range(n)), [1] * n
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]; x = parent[x]
return x
total, chosen = 0, []
for u, v, weight in sorted(edges, key=lambda edge: edge[2]):
a, b = find(u), find(v)
if a != b:
if size[a] < size[b]: a, b = b, a
parent[b] = a; size[a] += size[b]
total += weight; chosen.append((u, v, weight))
if len(chosen) != max(0, n - 1): raise ValueError("Graph is disconnected")
return total, chosen
print(kruskal(3, [(0, 1, 3), (0, 2, 1), (1, 2, 2)])[0])3
- 1
Edge order establishes the greedy cost choice. DSU representatives tell whether an edge would close a cycle in the already chosen forest.
- 2
Union by size and path compression keep component operations near constant amortised cost. The routine’s sorted edge pass remains the dominant standard term.
- 3
For E edges, sorting costs O(E log E); DSU adds near-linear work. A disconnected input is rejected instead of silently presenting a forest as one spanning tree.
04 Count the cost
O(E log E + V) with path compression and union by size
O(V + E) including sorted edges
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Use the cycle rule to reject a triangle’s third edge after two component merges.
Reveal one possible solution +
parent = list(range(3))
def find(x):
while parent[x] != x: x = parent[x]
return x
accepted = 0
for u, v in [(0, 2), (1, 2), (0, 1)]:
a, b = find(u), find(v)
if a != b: parent[b] = a; accepted += 1
print(accepted)06 Check your reasoning
When does Kruskal reject an edge?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.