Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Minimum Spanning Tree proof does not depend on a minor Python release.
Verify in Python docs(opens in a new tab)Connect every vertex of a weighted undirected graph with minimum total edge weight, without cycles. Select Prim or Kruskal from the representation, and distinguish spanning cost from source-to-node distances.
1 practice exercise2 interview problems
Recognize it when Every required vertex must be connected, but no particular source or route is privileged.
Checking your account…
A minimum spanning tree selects V minus one undirected edges that connect all vertices without cycles and minimize total edge weight. It optimizes network cost, not distance from a source.
For a cut that no already accepted forest edge crosses, a lightest crossing edge can extend that forest while preserving compatibility with some MST. Equal weights can give several equally optimal trees.
def is_spanning_tree(node_count,edges):
if len(edges)!=node_count-1:return False
parent=list(range(node_count))
def find(node):
while node!=parent[node]:parent[node]=parent[parent[node]];node=parent[node]
return node
for left,right in edges:
a,b=find(left),find(right)
if a==b:return False
parent[b]=a
return node_count>0 or not edgesImplement is_spanning_tree(node_count,edges). Undirected edges are [u,v]; return whether they connect all nodes without a cycle. node_count is a nonnegative integer; edge endpoints are valid indices in 0..node_count-1. An empty graph returns False because it has no spanning tree.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def is_spanning_tree(node_count,edges):
if len(edges)!=node_count-1:return False
parent=list(range(node_count))
def find(node):
while node!=parent[node]:parent[node]=parent[parent[node]];node=parent[node]
return node
for left,right in edges:
a,b=find(left),find(right)
if a==b:return False
parent[b]=a
return node_count>0 or not edgesAn MST may give a poor route between two vertices even though its total network weight is minimum. Shortest-path trees optimize source distances and can have different edges and total weight.
def minimum_spanning_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 minimum_spanning_weight(node_count,edges). Weighted undirected edges are [weight,u,v]; return MST weight or None if disconnected. node_count is a nonnegative integer; edge endpoints are valid indices in 0..node_count-1. An empty graph returns None under this spanning-tree contract.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def minimum_spanning_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 NoneRun the existing weight Lab on four vertices. The third cheapest edge closes a triangle; the fourth is necessary to reach vertex 3. Predict why the result is 7 rather than the sum of the three cheapest weights.
| Step | Executed statement | State | Why |
|---|---|---|---|
| First connection | a,b=find(left),find(right);parent[b]=a;size[a]+=size[b];total+=weight;used+=1 |
after edge [1,0,1]: total=1, used=1, component={0,1} |
The lightest edge crosses two separate components. |
| Extend component | a,b=find(left),find(right);parent[b]=a;size[a]+=size[b];total+=weight;used+=1 |
after edge [2,1,2]: total=3, used=2, component={0,1,2} |
The root of 1 is already 0; adding 2 still merges distinct components. |
| Reject closure | a,b=find(left),find(right);continue |
edge [3,0,2] skipped, total=3 |
Both endpoints have root 0; its low weight does not justify a cycle. The continue executes only after the actual same-root check. |
| Complete tree | a,b=find(left),find(right);parent[b]=a;size[a]+=size[b];total+=weight;used+=1;return total if used==node_count-1 else None |
after [4,2,3]: total=7, used=3 |
The final edge joins the isolated vertex, satisfying all four vertices. |
| Disconnected call | return total if used==node_count-1 else None |
used=1 instead of 3; result=None |
A finite partial cost does not establish spanning connectivity. |
| Output | |
|---|---|
print(minimum_spanning_weight(4, [[1,0,1],[2,1,2],[3,0,2],[4,2,3]])) |
7 |
print(minimum_spanning_weight(4, [[1,0,1]])) |
None |
A cut argument establishes safe choices; union-find establishes cycle prevention. Neither alone substitutes for the final connectivity check. Choose the interface and algorithm from the input representation before optimizing.
A graph with multiple components has no single spanning tree. Compute a minimum spanning forest only if the contract requests it; the weight Lab returns None instead. Its edge format is [weight,u,v].
Say: “I repeatedly choose a safe light edge crossing a component cut. Cycle prevention keeps a forest; V minus one accepted edges prove connectivity.” State undirected input, equal-weight ties, and disconnected behavior.
Python 3.11+
The code uses standard Python syntax and containers supported by the browser Judge. The Minimum Spanning Tree 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 |
|---|---|---|---|
| Kruskal with sorting and size-based union-find | O(E log(E + 1) + V + E alpha(V)) | O(E log(E + 1) + V + E alpha(V)) | The Lab sorts a new list and checks component roots. |
| Lazy-heap Prim | O(V + E log(E + 1)) | O(V + E log(E + 1)) | Obsolete heap entries are retained until popped; dense matrix Prim can instead take O(V^2). |
O(V + E) extra space for the sorted-edge or lazy-heap implementation.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
[5,0,1] means weight 5 and endpoints 0 and 1 in this Lab. Reading it as [u,v,weight] silently changes the cost.
Prevent it: Check the interface before unpacking.
left,right,weight = edgeweight,left,right = edgeWhere you will hit this: Measure a Minimum Spanning Tree(opens in a new tab)
Roots already equal mean the endpoints are connected. Adding their edge creates a cycle even if its weight is small.
Prevent it: Accept only unequal component roots.
accept = Trueaccept = root_left != root_rightWhere you will hit this: Measure a Minimum Spanning Tree(opens in a new tab)
Two accepted edges cannot connect four vertices. The sum is a component cost, not an MST for the whole graph.
Prevent it: Check the required accepted-edge count or connected-vertex count.
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