Skip to contentKEEP THE CRAFTTHE SANCTUARY

Minimum Spanning Tree

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…

Minimum Spanning Tree Code Labs

Connect Every Vertex with Minimum Total Edge Weight

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.

Use the Cut Property

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.

Check a Spanning Tree

Reference
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 edges
Practice

Implement 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.

Public tests

  • Require connectivity and no cycle

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Check a Spanning Tree

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 edges

Distinguish a Tree from Shortest Paths

An 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.

Compute Minimum Spanning Weight

Reference
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 None
Practice

Implement 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.

Public tests

  • Choose safe light edges across cuts

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compute Minimum Spanning 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 None

Reject a Cheap Cycle Before Connecting the Last Vertex

Run 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.
Print 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.

Handle Disconnected Graphs as a Forest

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].

Explain It in an Interview

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 Version Note

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)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Kruskal with sorting and size-based union-findO(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 PrimO(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).

Space

O(V + E) extra space for the sorted-edge or lazy-heap implementation.

Assumptions

  • V counts every required vertex, including isolated ones.
  • The weight Lab represents an edge as [weight,u,v]; other interfaces may order fields differently.

Invariants Worth Saying Aloud

  1. Accepted edges form a forest extendable to some minimum spanning tree.
  2. A cut respecting that forest has a safe minimum crossing edge.
  3. For V positive vertices, a connected acyclic result has V-1 edges.

When To Use Or Avoid Minimum Spanning Tree

Use It When

  • Use Kruskal for an edge list with component checks, or Prim for an adjacency-list growth frontier.
  • Allow negative weights and ties; they do not invalidate the minimum-spanning objective.

Choose Another Tool When

  • Directed arborescences require a different algorithm and contract.
  • A shortest-path tree minimizes distances from a source, not the sum of its tree edges.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Unpacking the wrong edge format

[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.

Avoid

left,right,weight = edge

Use instead

weight,left,right = edge

Adding an edge inside one component

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.

Avoid

accept = True

Use instead

accept = root_left != root_right

Returning a partial forest as a spanning tree

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.

Avoid

answer = total

Use instead

answer = total if used == node_count - 1 else None

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.