Skip to content
StackDecode
GraphsAnimated

Kruskal's Algorithm

Add edges cheapest first unless they form a cycle (union-find).

Time

O(E log E)

Extra space

O(V)

Use it for

Minimum spanning tree on sparse graphs.

How it works

  1. Sort all edges from cheapest to most expensive.
  2. Take the next edge. If it connects two nodes that are not yet connected, keep it; if they are already connected, it would make a cycle, so skip it.
  3. A union-find structure answers "already connected?" almost instantly.
  4. Stop after n − 1 edges. Those edges are a minimum spanning tree.

Watch it run

Loading animation…