Skip to interview prep
Apexed

216. How does Kruskal's algorithm build a minimum spanning tree?

MediumDisjoint sets

Technical

Type or dictate your answer. Your draft is saved on this device.

Show model answer

Sort the edges by weight and scan them in increasing order. Add an edge when its endpoints are in different union-find sets (it joins two components) and skip it when they share a set (it would form a cycle). Stop after V − 1 edges.

Correctness follows from the cut property: the lightest edge crossing any cut belongs to some MST. Time is O(E log E) for sorting, which is O(E log V), plus nearly linear union-find work; space O(V + E). It is a natural fit for sparse graphs given as edge lists.

Example program

How does Kruskal's algorithm build a minimum spanning tree — Data structures & algorithms interview question — Apexed