Skip to contentKEEP THE CRAFTTHE SANCTUARY

Kruskal

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 Code Labs

Process Edges by Increasing Weight

Kruskal considers undirected edges globally from lightest to heaviest. Accepted edges form a forest that gradually joins components.

Add Only Edges Joining 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.

Trace Kruskal Edge Decisions

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

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

Public tests

  • Reject edges within one component

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

Trace Kruskal Edge Decisions

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 trace

Track Components Through Sorted Edge Decisions

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

Use Union Find for Cycle Prevention

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.

Compute Kruskal MST Weight

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

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

Public tests

  • Stop after connecting all components

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

Compute Kruskal MST Weight

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 None

Choose Kruskal or Prim

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

Explain It in an Interview

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

Complexity & Invariants

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

OperationAverageWorstInterview note
Sorted edges with size-based union-findO(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.

Space

O(V + E) for component arrays and sorted list; decision-trace output adds O(E) rows.

Assumptions

  • The trace Lab uses path compression without size/rank, so do not automatically attribute the strongest size-plus-compression bound to it.
  • The trace visits every edge; the weight Lab also scans all edges even after a tree has formed.

Invariants Worth Saying Aloud

  1. Union-find partitions exactly the components of the accepted forest.
  2. Each accepted edge merges two components and reduces their count by one.
  3. The current forest is extendable to some MST; cycle edges cannot extend a tree.

When To Use Or Avoid Kruskal

Use It When

  • Use Kruskal with sorted edges and union-find for MST or an explicitly requested spanning forest.
  • Allow tied and negative weights; a deterministic tuple can settle output order without changing optimal cost.

Choose Another Tool When

  • Do not use global edge sorting to answer source-to-node shortest distances.
  • For a dense matrix, an O(V^2) Prim variant can be a simpler representation match.

Common Pitfalls

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

Sorting by endpoints instead of weight

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

Avoid

first = sorted(edges)[0][2]

Use instead

first = min(edges, key=lambda edge: edge[2])[2]

Comparing endpoints or immediate parents instead of roots

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.

Avoid

accepted = left != right

Use instead

accepted = find(left) != find(right)

Returning a forest without connectivity proof

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.

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.