Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Kruskal proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Sort undirected edges by weight and accept only those joining separate components. Track a safe forest and final connectivity, while separating the minimal weighted result from deterministic tie ordering.
1 practice exercise2 interview problems
Recognize it when The graph arrives as an edge list rather than a frontier-ready adjacency list.
Checking your account…
Kruskal considers undirected edges globally from lightest to heaviest. Accepted edges form a forest that gradually joins components.
An edge whose endpoints have different roots connects two trees and is safe by the cut property. Equal roots mean the edge closes a cycle and must be rejected.
def kruskal_trace(node_count,edges):
parent=list(range(node_count));trace=[]
def find(node):
if parent[node]!=node:parent[node]=find(parent[node])
return parent[node]
for edge in sorted(edges):
weight,left,right=edge;a,b=find(left),find(right);accepted=a!=b
if accepted:parent[b]=a
trace.append([edge.copy(),accepted])
return traceImplement kruskal_trace(node_count,edges). Edges are [weight,u,v]; return [edge,accepted] in sorted order. node_count is a nonnegative integer, edges use [weight,u,v], and every endpoint is in 0..node_count-1.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def kruskal_trace(node_count,edges):
parent=list(range(node_count));trace=[]
def find(node):
if parent[node]!=node:parent[node]=find(parent[node])
return parent[node]
for edge in sorted(edges):
weight,left,right=edge;a,b=find(left),find(right);accepted=a!=b
if accepted:parent[b]=a
trace.append([edge.copy(),accepted])
return traceRun the existing decision Lab with edges deliberately out of order. Predict the third row: it tests the weight-3 edge only after both endpoints have already joined the same component.
| Step | Executed statement | State | Why |
|---|---|---|---|
| Sort input | for edge in sorted(edges): |
weights=1,2,3,4 |
Input order does not decide which edge is tested first. |
| Merge first pair | a,b=find(left),find(right);accepted=a!=b;parent[b]=a;trace.append([edge.copy(),accepted]) |
after [1,0,1]: parent=[0,0,2,3], accepted=True |
A single accepted edge creates the component {0,1}. |
| Merge vertex 2 | a,b=find(left),find(right);accepted=a!=b;parent[b]=a;trace.append([edge.copy(),accepted]) |
after [2,1,2]: parent=[0,0,0,3], accepted=True |
find(1) returns 0 rather than the original endpoint 1. |
| Reject cycle | a,b=find(left),find(right);accepted=a!=b;trace.append([edge.copy(),accepted]) |
[3,0,2] has roots 0 and 0, accepted=False |
The trace retains rejected decisions, unlike the MST output edge set. |
| Join final component | a,b=find(left),find(right);accepted=a!=b;parent[b]=a;trace.append([edge.copy(),accepted]) |
after [4,2,3]: parent=[0,0,0,0], accepted=True |
All four vertices now share a component. |
| Output | |
|---|---|
print(kruskal_trace(4, [[3,0,2],[1,0,1],[4,2,3],[2,1,2]])) |
[[[1, 0, 1], True], [[2, 1, 2], True], [[3, 0, 2], False], [[4, 2, 3], True]] |
The decision Lab is not a full disconnected-result validator; the weight Lab supplies that final check. If ties matter to displayed edge order, document the secondary tuple key separately from the cut proof.
The weight Lab combines path compression with union by size for inverse-Ackermann amortized checks. The decision trace omits size/rank and should not inherit that guarantee merely because it compresses paths. In both, accepted-edge count tracks connectivity.
def kruskal_weight(node_count,edges):
parent=list(range(node_count));size=[1]*node_count;total=used=0
def find(node):
if parent[node]!=node:parent[node]=find(parent[node])
return parent[node]
for weight,left,right in sorted(edges):
a,b=find(left),find(right)
if a==b:continue
if size[a]<size[b]:a,b=b,a
parent[b]=a;size[a]+=size[b];total+=weight;used+=1
return total if used==node_count-1 else NoneImplement kruskal_weight(node_count,edges). Return MST weight or None when disconnected. node_count is a nonnegative integer, edges use [weight,u,v], and every endpoint is in 0..node_count-1. Zero nodes returns None under this spanning-tree convention.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def kruskal_weight(node_count,edges):
parent=list(range(node_count));size=[1]*node_count;total=used=0
def find(node):
if parent[node]!=node:parent[node]=find(parent[node])
return parent[node]
for weight,left,right in sorted(edges):
a,b=find(left),find(right)
if a==b:continue
if size[a]<size[b]:a,b=b,a
parent[b]=a;size[a]+=size[b];total+=weight;used+=1
return total if used==node_count-1 else NoneChoose Kruskal for edge lists or a requested spanning forest, and Prim for adjacency-based growth. Pre-sorted input helps only if the implementation avoids sorting again: these Labs still call sorted. Both return optimal cost with ties; deterministic edge selection requires a stated tie key.
Say: “The next lightest edge crossing two current components is safe; union-find rejects cycle edges.” Stop after V minus one accepted edges and report failure or a forest when components remain.
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Kruskal proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Sorted edges with size-based union-find | O(E log(E + 1) + V + E alpha(V)) | O(E log(E + 1) + V + E alpha(V)) | The weight Lab uses size and path compression; initialization is not free when E is small. |
O(V + E) for component arrays and sorted list; decision-trace output adds O(E) rows.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
With [u,v,weight] input, natural tuple order selects endpoint 0 first even when that edge costs 9.
Prevent it: Use the declared weight key or normalize to [weight,u,v].
first = sorted(edges)[0][2]first = min(edges, key=lambda edge: edge[2])[2]Where you will hit this: Kruskal's Minimum Spanning Tree(opens in a new tab)
In parent [0,0,1], node 2 reaches root 0 through node 1. Distinct endpoints and distinct immediate parents can still belong to the same component.
Prevent it: Complete find on both endpoints before accepting their connecting edge.
accepted = left != rightaccepted = find(left) != find(right)Where you will hit this: Kruskal's Minimum Spanning Tree(opens in a new tab)
A cheap accepted subset can leave vertices disconnected. It is not a whole-graph MST just because every edge avoided a cycle.
Prevent it: Check the accepted count against V-1.
answer = totalanswer = total if used == node_count - 1 else NoneWhere you will hit this: Maximum Container Area(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27