Minimum Spanning Tree (MST)
Proving correctness of any greedy algorithm is always a challenge. And of course it’s more challenging to find them in the first place - just look at how they’re named.
But it’s not relatively easy to code it up during a tech interview. And usually no one cares to discuss around the proof of correctness.
Tree vs. Graph
Tree is a connected graph without loops.
Prim - build vertices
- Start with a single vertex.
- Grow the tree by one edge. Find the minimum-weight edge that connects the tree to an outside vertex.
- Repeat step 2 until all vertices are in the tree.

Kruskal - builds edges
- Sort all the edges in ascending order of its weight.
- Choose the smallest edge. Check if it forms a cycle with any existing tree. If cycle is not formed, include this edge. Else, discard it.
- Repeat step 2 until there are (V-1) edges chosen.

Cycles - Disjoint Set / Union-Find
In Kruskal’s step 2. We need to detect cycles. Union-Find is an efficient algorithm in this scenario, instead of normal dfs with a visited set.
Key Ideas
- Each set is represented by a single element in the set. Every other elements are made to pointing to the element;
- Given a random element, we can find its set by looking at who it’s pointing to.
- To union two sets, just make one representative element pointing to the other.
Key Implementation
1 | |
Full Implementation
1 | |