Algorithms

Union-Find & Kruskal MST

Kruskal’s algorithm sorts edges by weight and adds each edge that connects two different components. Union-Find makes the cycle check nearly constant time.

8 minLevel 3/3The interactive stage stays ad-free.
Processed0 / 12Components8MST weight0
423758631149501234567

Edges are processed from lightest to heaviest. A cyan edge joins two different components and is accepted; a dashed red edge would create a cycle. The run is complete when n − 1 = 7 edges are accepted.

What you are seeing

1

Each node starts in its own component. A union merges two components into one.

2

Kruskal processes edges from lightest to heaviest. An edge is accepted only if its endpoints have different roots.

3

After n − 1 accepted edges, the result is a minimum spanning tree. Rejected edges would create a cycle.

Why it matters

Union-Find powers network design, clustering, image segmentation, and connectivity queries. Kruskal’s algorithm is one of the cleanest applications of greedy thinking.

Complexity & details

Sorting: O(E log E). Each union/find is nearly O(1) with path compression and union by rank.

Frequently asked questions

Why does Kruskal reject an edge?+

If both endpoints already share the same root, adding the edge would close a cycle. A spanning tree cannot contain a cycle.

What does path compression do?+

During find, every visited node is pointed directly at the root. Later queries on the same path become much faster.