Implementing Kruskal's Algorithm with Union-Find [00OW]
- October 12, 2026
Let's consider Kruskal's Algorithm more carefully. Here it is again, in pseudocode:
Algorithm Kruskal's Algorithm (pseudocode) [00OX]
- October 12, 2026
Analysis of naive Kruskal [00P1]
- October 14, 2026
How fast can Kruskal's Algorithm run? First of all, sorting the edges takes \Theta (E \lg E) time if we use a good sorting algorithm. Note that E is O(V^2) (the maximum number of edges is V(V-1)/2), so \lg E is O(\lg V^2) = O(2 \lg V) = O(\lg V). Hence we can simplify \Theta (E \lg E) to \Theta (E \lg V).
The rest depends a lot on how we check whether an edge e would complete a cycle. One obvious method is to do a graph search like DFS or BFS from one endpoint of e, using only edges already in T, and see if we can reach the other endpoint of e. If there is a path from one end of e to the other using only edges in T, it means that adding e would complete a cycle. Running a DFS or BFS in T takes \Theta (V + E) = \Theta (V) (since T will never have more edges than vertices), and we do this check once for each edge, giving a total of \Theta (VE), which dominates the \Theta (E \lg V) time to sort the edges. Of course, \Theta (VE) can be as big as \Theta (V^3) if there are a lot of edges. Can we do better?
Union-find motivation [00P2]
- October 14, 2026
Notice that for each edge e = (u,v), doing a DFS is sort of overkill, in the sense that it actually tries to find a path from u to v—but we don’t care about the path, only whether u and v are already connected or not. In this case—when we only care about which vertices are connected and not about the actual paths between them—it turns out that we can test for connectivity much faster.
The basic idea is to come up with some sort of data structure to maintain a set of connected components. Given such a data structure, the algorithm looks something like this:
- Start every vertex in its own connected component.
- For each edge, test whether its vertices are in the same component (which means it would form a cycle) or in different components.
- If the endpoints are in different components, add the edge to T, and merge the two components into one.
This kind of data structure is called a union-find structure (or a disjoint-set data structure), and from the algorithm sketch above we can see what operations it needs to support:
- \mathsf {MakeSets}(n): create a union-find structure containing n singleton sets labelled 0 \dots n-1.
- \mathsf {Find}(v): return the name of the set containing v. (“Name” could be anything; typically we will use integers.) To check whether two vertices u and v are in the same connected component, we can test if \mathsf {Find}(u) = \mathsf {Find}(v).
- \mathsf {Union}(x,y): merge the two sets containing x and y.
This kind of data structure actually has lots of applications besides implementing Kruskal's Algorithm; you can explore one such application on a homework problem.
Algorithm Kruskal's Algorithm (with union-find) [00P3]
- October 14, 2026
Given a union-find data structure, we can implement Kruskal's Algorithm as follows:
Analysis of Kruskal with union-find [00P4]
- October 14, 2026
Let's analyze this version of Kruskal's Algorithm with union-find, to discover how fast we would like the union-find operations to be!
- Sorting edges by weight takes time \Theta (E \log V), as before.
- We do 2E \mathsf {Find} operations, because we call it twice for each edge to check whether adding that edge would make a cycle.
- We only call \mathsf {Union} when adding an edge, and since we are making a tree, we will do this at most V - 1 times.
Union-find design and analysis [00PD]
- October 15, 2026
We previously introduced the idea of a union-find structure; we will now see how to actually implement it efficiently.
Some bad ideas for implementing union-find [00P5]
- October 14, 2026
How can we implement a union-find data structure? One simple idea is to just keep a dictionary that maps each item to an "id" which identifies which set it is in.
- \mathsf {Find} takes \Theta (1), assuming we can do \Theta (1) dictionary lookup (e.g. using a hash table).
- To do \mathsf {Union}, however, we have to go through every single item to find which ones are in the set we want to change, and change them all to the other set. This takes \Theta (n), which is too slow.
We could also try to flip things around and keep a dictionary mapping each set id to a list of items in that set.
- \mathsf {Union} is now \Theta (1) (assuming we use something like linked lists), since we can just append one list to the other.
- However, \mathsf {Find} is now \Theta (n): to find an item we simply have to go through every list looking for it.
Can we somehow get the best of both worlds?
Idea: union-find via "lazy ids" [00P6]
- October 14, 2026
It turns out that the first idea above (having a dictionary mapping every item to an id for its set) is a good starting place. \mathsf {Union} took too long since we had to update every single item in a set to reference a new set. But what if we didn't have to update all of them?
We can do this if we allow ourselves a bit of indirection: rather than having every item reference its set, we can have every item either reference its set or another item in the same set. Imagine arranging all the items in a set into a tree: the item at the root is the only one that directly references the identity of the set (in fact, we can use the root item itself as the "name" of the set, like naming a group after its leader); every other item references some other item in the set, but ultimately if we keep following references we always end up at the root. Now, in order to change the identity of a set, we only need to update the root item itself; all the other items just "come along for the ride".
Union-find implementation [00PC]
- October 15, 2026
Based on the above ideas, we can implement a union-find structure as follows.
- We keep track of an array/dictionary mapping each item to its parent. Any item which maps to itself is considered a "root". This represents a forest, that is, a collection of trees; each tree consists of items which are all in the same set.
- We also keep track of an array/dictionary mapping every root item to the height of its tree. Tracking the heights of the trees is important so that we can implement union in a reasonable way. Non-root items will be ignored, so it does not matter what they map to. In other words, once an item stops being a root, we will stop worrying about keeping its height updated.
Given these mappings, we can implement the union-find operations as follows.
- To create a fresh union-find structure, create the parent dictionary mapping every item to itself (since every item starts in its own singleton set), and the height dictionary mapping every item to 0 (every item is the root of its own trivial tree of height 0).
- To implement \mathsf {Find}(u), repeatedly finding the parent, grandparent, etc. of u until finding a root.
- To implement \mathsf {Union}(u,v):
- Use \mathsf {Find} to get the roots of u and v’s trees.
- If the roots are the same, do nothing.
- If the roots are different, make the root with the smaller height the child of the root with the bigger height. If the heights are the same, it doesn’t matter which becomes a child of the other, but you must then increment the height of the new parent.
Union-find analysis [00PE]
- October 15, 2026
How long do these operations take? Clearly \mathsf {Union} takes T_{\mathsf {Find}} + \Theta (1). So implementing \mathsf {Find} efficiently is the crux of the issue. It seems like it might take \Theta (n) in the worst case, if we end up with an unbalanced tree—for example, if all the items in a tree end up in a long linear chain. But it turns out that being careful in how we implement \mathsf {Union}, taking heights into account, means this will never happen! The following theorem tells us something about what the resulting trees can look like.
Theorem Union-find trees are balanced [00PG]
- October 16, 2026
If we start from a freshly created union-find structure and call \mathsf {Union} any number of times (with the implementation outlined above), every tree of height h contains at least 2^h items.
Proof.
- October 16, 2026
Subproof. Union-find trees are balanced ›
- October 16, 2026
Subproof. Union-find trees are balanced ›
- October 16, 2026
For the induction case, suppose that any tree of height k contains at least 2^k items; we must show this is also true for trees of height k+1.
So suppose there is a tree of height k+1. The way \mathsf {Union} works, the height associated with a root only increases (by exactly one) when forming the union of two trees that previously had the same height. So the tree of height k+1 was, at some point, formed from the union of two trees of height k. By the induction hypothesis, those trees contained at least 2^k items each; hence the new, merged tree of height k+1 has at least 2^k + 2^k = 2^{k+1}. There could have been additional union operations since that one, but they could only increase the number of items.
Corollary \mathsf {Find} and \mathsf {Union} run in \Theta (\lg n) [00PH]
- October 16, 2026
\mathsf {Find} (and hence \mathsf {Union}) takes time \Theta (\lg n) in the worst case.
Proof.
- October 16, 2026
Remark Path compression [00PI]
- October 16, 2026
One can also implement path compression: when doing \mathsf {Find}, update every node along the search path to point directly to the root. This does not make \mathsf {Find} asymptotically slower, and it speeds up subsequent \mathsf {Find} calls. One can show (although the proof is somewhat involved—it would probably take two lectures or so) that \mathsf {Find} then takes essentially \Theta (\lg ^* n) on average, where \lg ^* n is the iterated logarithm of n, defined as the number of times the \lg function must be iterated on n before reaching a result of 1 or less. This means that the largest number for which \lg ^* n = k is n = 2^{2^{2^{\ldots }}} with k copies of 2 stacked up in a tower of exponents! So, for example, \lg ^* n \leq 5 for all n \leq 2^{2^{2^{2^2}}} = 2^{2^{2^4}} = 2^{2^{16}} = 2^{65536}, a number with 19729 decimal digits (for comparison, the number of particles in the entire universe is estimated at around 10^{80}, a number with a measly 81 decimal digits). So although in theory \lg ^* n is not a constant—it does depend on n, and can get arbitrary large as long as n is big enough—in practice, in our universe, it is essentially a constant (and a rather small constant at that). This means that both \mathsf {Find} and \mathsf {Union} can be implemented to run in (essentially) constant time!
Note, however, that this does not change the asymptotic running time for Kruskal’s algorithm, which is still dominated by the \Theta (E \log V) time needed to sort the edges.