Skip to content
Hello Python
Algorithm1 Practice2 Interview

Minimum Spanning Tree

Connect every vertex with minimum total edge weight while keeping the result acyclic. Learn the algorithm's preconditions, state transition, correctness argument, Python cost model, and transfer from one focused drill to a full Interview Problem.

Recognize it when

Consider Minimum Spanning Tree when the prompt's constraints and required operations match this shape: Connect every vertex with minimum total edge weight while keeping the result acyclic.

Pybit demonstrates Minimum Spanning Tree in a professional Python interview workspace.
On this page · Connect Every Vertex with Minimum Total Edge Weight

Checking your account…

Sign in to save your code and progress across devices. The lesson and problem statement remain public.

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 any cut separating vertices, a lightest edge crossing that cut is safe for some MST. Prim and Kruskal apply this property with different evolving cuts.

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.

Public tests

  • Require connectivity and no cycle

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

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.

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

Handle Disconnected Graphs as a Forest

A disconnected graph has no spanning tree. Return failure when one tree is required, or explicitly produce a minimum spanning forest by running the algorithm across components.

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
Minimum Spanning Tree complete workflowO(E log E)O(E log E)Run Kruskal with union-find and verify that exactly V-1 edges were accepted.

Space

O(V) for the focused Measure a Minimum Spanning Tree implementation.

Assumptions

  • The cut property makes every lightest edge joining two current components safe. Union-find rejects cycles; V-1 accepted edges connect all vertices and therefore form an MST.
  • The bound counts Python sorting, slicing, hashing, heap, recursion, and container-copy costs rather than treating syntax as free.

Invariants Worth Saying Aloud

  1. State the precise Minimum Spanning Tree invariant before coding and preserve it after every update, traversal step, or recursive return.
  2. The selected edges remain acyclic.
  3. Each accepted edge reduces the number of disconnected tree components by one.
  4. Accept an edge only when it joins distinct components. Preserve this claim after every transition.
  5. Require exactly V-1 accepted edges. Preserve this claim after every transition.

When To Use Or Avoid Minimum Spanning Tree

Use It When

  • Use Minimum Spanning Tree when this precondition is stated or can be proved: The weighted graph is undirected, and the required output connects each component without cycles.
  • Use it when this maintained state removes repeated work: The selected edges remain acyclic.

Choose Another Tool When

  • Avoid Minimum Spanning Tree when this precondition is absent: The weighted graph is undirected, and the required output connects each component without cycles.
  • Avoid it when a simpler direct scan satisfies the constraints with less implementation risk.

Common Pitfalls

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

Applying the algorithm without its precondition

Verify algorithm preconditions such as sorted input, nonnegative weights, acyclicity, or admissible heuristics before applying it.

Prevent it: State and verify this precondition before coding: The weighted graph is undirected, and the required output connects each component without cycles.

Avoid

def minimum_spanning_weight(node_count, edges):
    pass

Use instead

def minimum_spanning_weight(node_count, edges):
    if node_count <= 1:
        return 0
    parent = list(range(node_count))
    size = [1] * node_count
    def find(node):
        while node != parent[node]:
            parent[node] = parent[parent[node]]
            node = parent[node]
        return node
    total = used = 0
    for left, right, weight in sorted(edges, key=lambda edge: edge[2]):
        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
        if used == node_count - 1: break
    return total if used == node_count - 1 else -1

Breaking the state transition

Adds the lightest edges without rejecting cycles.

Prevent it: Preserve this proof obligation: The cut property makes each chosen minimum crossing edge compatible with some minimum spanning tree.

Avoid

def minimum_spanning_weight(n,edges):
    return sum(edge[2] for edge in sorted(edges,key=lambda e:e[2])[:n-1])

Use instead

def minimum_spanning_weight(node_count, edges):
    if node_count <= 1:
        return 0
    parent = list(range(node_count))
    size = [1] * node_count
    def find(node):
        while node != parent[node]:
            parent[node] = parent[parent[node]]
            node = parent[node]
        return node
    total = used = 0
    for left, right, weight in sorted(edges, key=lambda edge: edge[2]):
        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
        if used == node_count - 1: break
    return total if used == node_count - 1 else -1

Hiding Python work in the claimed bound

Include visited state, boundary cases, recursion depth, and hidden copying costs in correctness and complexity analysis.

Prevent it: Count every sort, slice, copy, membership check, heap update, and recursive frame before claiming O(E log E).

Avoid

def minimum_spanning_weight(n,edges):
    return sum(edge[2] for edge in sorted(edges,key=lambda e:e[2])[:n-1])

Use instead

def minimum_spanning_weight(node_count, edges):
    if node_count <= 1:
        return 0
    parent = list(range(node_count))
    size = [1] * node_count
    def find(node):
        while node != parent[node]:
            parent[node] = parent[parent[node]]
            node = parent[node]
        return node
    total = used = 0
    for left, right, weight in sorted(edges, key=lambda edge: edge[2]):
        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
        if used == node_count - 1: break
    return total if used == node_count - 1 else -1

Reviewed References

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