← Lessons

quiz vs the machine

Gold1410

Algorithms

Kruskal with Union Find Deep

Build a minimum spanning tree by adding the cheapest edges that do not form a cycle, tracked with a disjoint set structure.

6 min read · core · beat Gold to climb

Edges in sorted order

Kruskal builds a minimum spanning tree by considering edges from cheapest to most expensive. It adds an edge only if its two endpoints currently belong to different components, since joining the same component would create a cycle.

Union find

The cycle check needs to ask whether two nodes are already connected. A disjoint set structure answers this efficiently. Each node points toward a representative of its component. Two optimizations make it nearly constant time:

  • Path compression flattens chains during lookups.
  • Union by rank attaches the smaller tree under the larger.

The flow is: sort edges, then for each edge find the representatives of both endpoints; if they differ, union them and keep the edge.

Key idea

Kruskal sorts edges and greedily keeps the cheapest that joins two separate components, using a union find structure with path compression and union by rank to test connectivity almost instantly.

Check yourself

Answer to earn rating on the learn ladder.

1. When does Kruskal keep an edge?

2. What do path compression and union by rank improve?