Problem Statement

Kruskal's MST

You have a bunch of dots (we call them nodes) connected by lines (we call them edges). Each line has a cost, called its weight. Your job is to connect every dot together using some of these lines, while paying the smallest total cost possible. The set of lines you pick is called a Minimum Spanning Tree, or MST. "Spanning" means it touches every dot, and "minimum" means the total weight is as small as it can be. Think of the dots as towns and the lines as roads with different building costs. You want every town reachable, for the cheapest total. Kruskal's algorithm is a simple, greedy way to do this: look at the lines from cheapest to most expensive, and grab each one as long as it does not form a loop.

mediumGraphUnion FindGraphsTime: O(E log E) · Space: O(V)

Signals to notice

build MST by sorting all edgesadd edges that don't create cyclesunion-find for cycle detection

Brute force first

Try all possible edge subsets that form a spanning tree — exponential. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Kruskal's: sort all edges by weight. Process edges cheapest first — add an edge if it connects two different components (Union-Find check). Stop after V-1 edges. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Trace it on n=4, edges=[[0,1,1],[0,2,4],[1,2,2],[2,3,3]]

sort by weight -> [[0,1,1],[1,2,2],[2,3,3],[0,2,4]]; parent=[0,1,2,3], total=0
edge(0,1,w=1): find(0)=0 != find(1)=1 -> union, total=1, parent=[0,0,2,3]
edge(1,2,w=2): find(1)=0 != find(2)=2 -> union, total=3, parent=[0,0,0,3]
edge(2,3,w=3): find(2)=0 != find(3)=3 -> union, total=6, parent=[0,0,0,0]
edge(0,2,w=4): find(0)=0 == find(2)=0 -> same component, skip (cycle)
all edges processed -> return total = 6

What must stay true

The cheapest edge that connects two different components is always safe to add to the MST (cut property). Union-Find efficiently checks and merges components. As long as that statement keeps holding, you can trust the steps built on top of it.

Shape of the loop

sort edges by weight ascending
parent = each node its own root
total = 0
for (u, v, w) in edges:
    if find(u) != find(v):   # endpoints in different components
        union(u, v); total += w
return total

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not stopping after V-1 edges — a spanning tree of V vertices has exactly V-1 edges. Processing more is wasted work. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Graphs Pattern