Greedy Algorithms [00NJ]
- September 28, 2026
Introduction [00NK]
- September 28, 2026
Our next unit covers greedy algorithms—an important class of algorithms where repeatedly making the locally best choice (i.e. a "greedy" choice) results in a globally best result. This does not always work—but when it does, it is very effective. Typically, to prove that greedy algorithms are correct we can use some kind of exchange argument, where we imagine exchanging the greedy choice for some other choice, and show that it could only possibly make the result worse.
Weighted graphs [00NP]
- October 2, 2026
So far we have considered undirected and directed graphs, but each edge either exists or not. We will now consider weighted graphs, where each edge has some sort of cost.
Definition Weighted graph [00NN]
- October 2, 2026
A weighted (directed or undirected) graph is a graph where each edge is assigned a weight. That is, formally, there is a function w : E \to W which assigns to each edge e \in E a weight w(e) taken from a suitable set of weights W. The weight of an edge (u,v) is also denoted w(u,v) or w_{uv}.
The weight or length of a path is just the sum of the weights of its edges.
Remark ★ What kind of things can we use for weights? [00NO]
- October 2, 2026
For now, we will typically consider the set of weights W = \mathbb {R}^+, that is, nonnegative real numbers; later, we will consider W = \mathbb {R} and include the possibility of negative weights.
In general, one can use other sets besides real numbers for weights. For example, we could use integers, or natural numbers, or rational numbers. In fact, one can use any ordered semiring: there must be two operations corresponding to combining weights in series and in parallel (typically, for finding shortest paths, we combine weights in series by adding them, and in parallel by taking the minimum), these two operations must play nicely together, and there must also be some notion of "less than" which also plays nicely with the operations.
Remark Unweighted graphs as weighted graphs [00NQ]
- October 2, 2026
Note that we can usually think of an unweighted graph as a weighted graph where all edges have weight 1.
Dijkstra's Algorithm [00NL]
- September 28, 2026
The basic ideas behind Dijkstra's algorithm are first introduced via a POGIL activity.
Single-Source Shortest Paths [00NW]
- October 3, 2026
Dijkstra's Algorithm solves the single-source shortest path (SSSP) problem in a directed, weighted graph: given a vertex s, find the shortest paths from s to every other vertex in the graph.
Note that this seems like a harder problem than just finding the shortest path from s to some particular target vertex t, but it's really not. Intuitively, you can’t find the shortest path from s to t without exploring the rest of the graph, thus discovering shortest paths from s to other vertices along the way.
Dijkstra's Algorithm intuition [00NX]
- October 3, 2026
In an unweighted graph, we can use BFS to find shortest paths, but now we need to take edge weights into account. Intuitively, BFS searches outwards one layer at a time, by increasing distance. We’ll do the same thing: search outward by increasing distance. Imagine turning on a source of water at vertex s, and watching the water flood the whole graph. Each edge is a (directed) pipe, and the weight of an edge says how long the water takes to traverse that pipe. We can keep track of "where the water has reached" so far, and note at each step the next vertex reached by the water. Since the water floods in every direction possible, it is guaranteed that the time the water first reaches a vertex corresponds to the shortest path to that vertex from s.
Note that this only makes sense when the edge weights are positive—if water can “travel back in time” it invalidates this whole scheme; we can’t necessarily find the next vertex to be reached by the water with a greedy approach. If we want to find shortest paths when edge weights can be negative, we need a different algorithm (which we will study later).
Algorithm Dijkstra's Algorithm (basic version) [00NY]
- October 3, 2026
Here’s the basic algorithm, which we can think of as a generalization of BFS to weighted graphs. Recall that BFS keeps track of:
- which vertices have been visited so far,
- a layer map, giving the layer of each visited vertex, and
- a parent map recording the parent of each vertex in the BFS tree.
Theorem Correctness of Dijkstra's Algorithm [00NZ]
- October 3, 2026
Dijkstra’s algorithm correctly solves the SSSP problem for a weighted graph with nonnegative edge weights.
Proof.
- October 3, 2026
- At the start of the algorithm, s is the only visited vertex, and d[s] = 0 is correct since there are no negative-weight edges (and hence no better way to get from s to itself than just staying there).
- Now suppose the invariant holds and the loop executes one more time. Let u, v be the vertices picked by the algorithm. We will show that any other path from s to v must be at least as long as the path from s to v via u. Any other path from s to v must cross from a visited vertex to an unvisited vertex at some point, say it does this on the edge x \to y. But by the way u and v were chosen, we know that the shortest path from s to y via x is at least as long as the path from s to v (since by the invariant we know the shortest path from s to x), plus there may be extra distance from y to v as well. (Notice how the assumption of nonnegative edge weights is important here—if the distance from y to v could be negative it invalidates this proof!)
Hence, the loop updates the set of visited vertices and d appropriately and the invariant still holds.
Running time of Dijkstra's Algorithm (basic) [00O0]
- October 3, 2026
How long does the basic version of Dijkstra's Algorithm take? It depends a lot on how we choose vertices u and v on each iteration. A brute-force approach is to simply iterate over all edges (u,v), keep only those where u is visited and v unvisited, and remember the one with the smallest value of d[u] + w_{uv}. Since the while loop marks one vertex visited on each iteration, it executes |V| times, making the whole algorithm \Theta (VE) (which could be O(V^3) if the edges are dense). However, it turns out we can do better than this if we use a more clever scheme for quickly finding the best edge at each iteration. (Note that the best algorithms for solving the SSSP problem where negative weights are allowed run in \Theta (V^3) or \Theta (VE); we will learn about one such algorithm later in the semester.)
More efficient Dijkstra's algorithm [00O2]
- October 5, 2026
Can we do better than \Theta (VE)? The key, as usual, is to use some data structures to keep track of enough information so that we can pick u and v quickly without having to search through the whole graph every time.
Priority queue for Dijkstra [00O3]
- October 5, 2026
- We will expand d to keep track of not just the shortest distances to vertices, but the current shortest known distances to other vertices as well. So d[v] will always be an upper bound on the shortest distance from s to v. We may have to update d[v] every time we add a vertex u to S with an edge (u,v).
- We will expand the \mathit {parent} map similarly: \mathit {parent}[v] is the predecessor of v along the currently shortest known path from s.
The idea is that at each iteration we want to pick the unvisited vertex v with the smallest d[v]. We will store the unvisited vertices in some kind of data structure so that we can quickly remove the one with the smallest d[v]. We then need to be able to update d and \mathit {parent} appropriately.
So we need a data structure that allows us to:
- Add new items with a given value
- Remove the item with the smallest value
- Update the value of an existing item
Algorithm Dijkstra's Algorithm [00O4]
- October 5, 2026
Here is the updated version of Dijkstra's Algorithm using a priority queue for tracking unvisited vertices.
Remark Dijkstra in practice [00O5]
- October 7, 2026
Most standard libraries I am aware of do not have a priority queue implementation capable of doing a fast \mathit {updateKey} operation. One can simply remove an element and re-insert it, but this takes \Theta (n) since there is no way to find an element other than scanning over the entire heap. An implementation supporting a fast \mathit {updateKey} could, for example, keep a hash table on the side which keeps track of the location of each item within the heap. Given a sorted set data structure, it is also possible to keep a sorted set of (distance, vertex) pairs. Removing the vertex with the minimum distance is easy since it is just the first pair in the set; updating the distance of a vertex can be done by first deleting the (old distance, vertex) pair from the set (which can be done in O(\lg n) since the set is sorted) and then inserting (new distance, vertex).
Dijkstra runtime analysis [00O6]
- October 7, 2026
What’s the time complexity of this better implementation of Dijkstra's Algorithm? Again, we can’t just simplistically look at loops and so on. Instead, we count the total time taken by various operations. Let’s say our priority queue takes time T_{\mathit {rem}}(n) to do a remove-min operation on a priority queue of size n, and T_{\mathit {upd}}(n) to do an update-key operation.
- For any reasonable implementation of Q, creating it in the first place takes \Theta (V) time since we are inserting vertices with known keys all at once.
- We end up calling \mathit {removeMin} once for each vertex, and Q has size at most |V|, which contributes \Theta (V \cdot T_{\mathit {rem}}(V)) (the priority queue decreases each time, but half the calls are on a priority queue of size at least V/2, so we are still justified in saying it takes \Theta (V \cdot T_{\mathit {rem}}(V))).
- We also call \mathit {updateKey} at most once for each edge, which contributes O(E \cdot T_{\mathit {upd}}(V)).
- All other operations (e.g. setting values in d and \mathit {parent}) take \Theta (1), which adds \Theta (V + E) overall.
So in total, the algorithm takes \Theta (V \cdot T_{\mathit {rem}}(V) + E \cdot T_{\mathit {upd}}(V)). We’ll generally assume that |E| \geq |V| (otherwise the graph is either a tree, in which case we don’t need this algorithm, or there are degree-zero vertices which we can throw away). The total running time depends on the implementation of Q:
- We could simply use an array of vertices. Finding and removing the vertex with the smallest d value thus takes \Theta (n) (via linear search); updating the distance value also takes \Theta (n) since we have to do another linear search to find the required vertex. Substituting, this yields an overall time of \Theta (V \cdot V + E \cdot V) = \Theta (EV) (since we are assuming |E| \geq |V|).
- We could keep the array sorted by d value. Assuming we keep the vertex with the smallest d value at the end, removing it can be done in \Theta (1). To update the distance of a vertex requires a linear search to find the vertex and then linear time to insert it into its new sorted position. Thus overall this is \Theta (V \cdot 1 + E \cdot V) = \Theta (EV), no better than an unsorted array.
- We could use a dictionary (implemented as an array or hash table) mapping each vertex to its distance value. Updating is now \Theta (1), since we can just immediately access the value for a given vertex. However, finding and removing the vertex with minimum distance is \Theta (n) since we have to just scan through all the vertices to find the minimum. Overall, this takes \Theta (V \cdot V + E \cdot 1) = \Theta (V^2) (since E is O(V^2)).
- If we use a binary min-heap to store vertices by distance, we can remove the smallest-distance vertex in \Theta (\lg n). Updating a specific vertex is a bit tricker: we can keep some kind of hash table on the side so we know where to find a given vertex in the heap; then moving it up or down the heap to restore the heap properties after changing the distance value takes \Theta (\lg n). Hence, overall, Dijkstra with a binary heap takes \Theta (V \lg V + E \lg V) = \Theta (E \lg V).
- Finally, there is a data structure called a Fibonacci heap which allows updating in \Theta (1) and removing the minimum in \Theta (\lg n), in which case Dijkstra takes \Theta (V \lg V + E) overall. We won't learn more about Fibonacci heaps but you can read about them if you wish.
Technically, using a Fibonacci heap yields the fastest known implementation of Dijkstra's Algorithm, but Fibonacci heaps are complex to implement and rarely make a big difference in practice. \Theta (V \lg V + E) is better than \Theta (E \lg V) only if E is large relative to V, that is, if the graph is fairly dense. Using a binary heap tends to be the best all-around implementation.
Minimum spanning trees [00O7]
- October 9, 2026
Some of the information in this section is presented via two POGIL activities: Minimum Spanning Trees, Kruskal's Algorithm and the Cut Property.
Motivation [00O8]
- October 9, 2026
Suppose we have a number of vertices (locations, items, people, ...) and potential connections between them, where each connection has a cost (distance, money, ...). We want to pick some of the potential connections such that all vertices are connected, but the total cost is as small as possible.
For example, suppose there are a number of cities, and we can build train lines between certain pairs of cities for some particular cost. Some train lines might be more expensive (because they have to go over mountains, or over a bridge, or because they are very long) and some might be cheaper. What is the minimum amount of money we can spend building train lines such that it is possible to travel between any pair of cities by train?
These ideas suggest the following definitions.
Spanning subgraphs and minimum spanning trees [00O9]
- October 9, 2026
Definition Spanning subgraph [00OA]
- October 9, 2026
Let G = (V,E) be an unweighted graph with vertices V and edges E. A spanning subgraph of G is a connected graph V,E' where E' \subseteq E.
That is, a spanning subgraph of G is a connected graph with the same vertices as G and a subset of the edges; to make a spanning subgraph of G we pick some edges which connect all the vertices.
Remark Observations about spanning subgraphs [00OB]
- October 9, 2026
A few observations about spanning subgraphs:
- If G is connected, then G is a spanning subgraph of itself.
- If G is disconnected, it has no spanning subgraph, because deleting edges can't make it connected.
- If a spanning subgraph of G contains a cycle, then removing any edge from the cycle results in another spanning subgraph.
Definition Minimum-weight spanning subgraph [00OC]
- October 9, 2026
A minimum-weight spanning subgraph (MWSS) of an undirected, weighted graph G is a spanning subgraph with the smallest possible total weight.
Remark A graph can have multiple MWSS [00OD]
- October 9, 2026
Note that a graph can have multiple minimum-weight spanning subgraphs. For example, consider a triangle graph where all the edges have weight 1. Picking any two of the edges results in a minimum-weight spanning subgraph.
It turns out that if every edge has a unique weight, then the MWSS is unique, although this is not necessarily obvious!
Remark A MWSS does not contain shortest paths! [00OE]
- October 9, 2026
It is worth emphasizing that although a MWSS contains a path between any two vertices, that path may not be the shortest path. The MWSS is guaranteed to have the smallest total weight, but for individual pairs of vertices the path between them may be longer than necessary, because it allows us to connect all the vertices in the most efficient way overall.
As an example, consider a triangle graph T with three edges of weights 2, 2, and 3. To make an MWSS, we obviously want to pick the two edges of weight 2. But notice that the shortest path in T between the two endpoints of the weight-3 edge is of length 3, whereas the path between them in the MWSS has total length 4.
Theorem Every MWSS is a tree [00OF]
- October 9, 2026
In a weighted, undirected graph with positive edge weights, any minimum-weight spanning subgraph must be a tree.
Proof.
- October 9, 2026
Subproof. Every MWSS is a tree ›
- October 9, 2026
Subproof. Every MWSS is a tree ›
- October 9, 2026
Definition Minimum spanning tree [00OG]
- October 9, 2026
Because of the previous theorem, a minimum-weight spanning subgraph is usually referred to as a minimum spanning tree, or MST.
Algorithms for computing MST [00OH]
- October 9, 2026
Here are three algorithms to compute a minimum spanning tree:
- Kruskal's Algorithm: repeatedly pick the shortest edge that doesn't complete a cycle with other already-picked edges.
- Prim's Algorithm: repeatedly pick the shortest edge that connects a visited vertex to an unvisited vertex and doesn't complete a cycle.
- Reverse-delete: repeatedly delete the longest edge that doesn't disconnect the graph.
It's kind of amazing that all these greedy approaches work. It's almost like we can't mess it up no matter what we try. But how do we know that they work?
Proving MST algorithms correct [00OI]
- October 9, 2026
Proving the correctness of all the algorithms mentioned above relies on one crucial property.
Definition Cut [00OL]
- October 9, 2026
A cut in a graph G = (V,E) is a partition of the vertices V into two sets S and T, that is, every vertex is in either S or T but not both. We say that an edge e crosses the cut (S,T) if one vertex of e is in S and the other is in T.
Theorem Cut property [00OJ]
- October 9, 2026
Let G = (V,E) be an undirected, weighted graph with positive weights. Suppose S and T partition V, and let e = (x,y) be an edge crossing the (S,T) cut, such that the weight of e is strictly smaller than the weight of any other edge crossing the (S,T) cut. Then every minimum spanning tree of G must contain e.
Proof.
- October 9, 2026
Let G be a weighted, undirected graph G = (V,E), let S and T be an arbitrary partition of V into two sets, and suppose e = (x,y) is the smallest-weight edge with one endpoint in S and one in T. We wish to show that any MST of G must contain e.
We will prove the contrapositive. Suppose M is a spanning tree of G which does not contain the edge e; we will show that M is not a minimum spanning tree. Since M is a tree, it contains a unique path between any two vertices. So consider the unique path in M between x and y. It must cross the cut at least once since it starts in S and ends in T; suppose it crosses at e' = (x',y'),with x' \in S and y' \in T. We know that the weight of e is smaller than the weight of e', since e was defined to be the smallest-weight edge crossing the (S,T) cut. Now take M and replace e' with e; the result is still connected (because any path using e' can be rerouted through e), but it has a smaller total weight because the weight of e is less than e'.
So, we have shown that any spanning tree M which does not contain the edge e can be made into a smaller one, which means that M is not a minimum spanning tree.
Remark Exchange arguments [00OK]
- October 9, 2026
This is an exchange argument, which is a general technique for proving that something is not minimal (and, more generally, for proving that greedy algorithms are correct)—find appropriate things to exchange so the total becomes smaller (while preserving any relevant properties).
In this particular example, note that we can’t exchange e with any edge across the cut! We particularly found the edge on the path from x to y since that guarantees we can exchange it with e while preserving connectivity.
Theorem Kruskal's Algorithm is correct [00OM]
- October 9, 2026
Kruskal’s Algorithm is correct (when all edges have distinct weights).
Proof.
- October 9, 2026
Remark Kruskal on graphs with repeated weights [00ON]
- October 9, 2026
The previous theorem applies only to graphs where every edge has a distinct weight, but it is not too much harder to show that Kruskal's Algorithm works even when there are repeated weights.
Remark Prim and Reverse-Delete are correct [00OP]
- October 9, 2026
Prim's Algorithm and the Reverse-Delte algorithm are correct as well, by similar arguments.
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.