Privacy note: We capture your IP address to provide customised and focused services. See our Privacy Policy.

Algorithms & Competitive Programming — Alpha School

Lesson 14: Greedy Algorithms and Union-Find

A greedy algorithm builds a solution by making the best immediate choice at each step, never looking back. It sounds reckless — and sometimes it is — but for a surprising number of problems the greedy choice is provably correct. The classic example is the activity selection problem: given a set of activities with start and finish times, choose the largest number of non-overlapping activities. The greedy rule is to always pick the activity that finishes earliest. It works, and the reason is an exchange argument: any optimal solution can be swapped to include the earliest-finishing activity without making it worse.

The danger is assuming greed works when it does not. The coin change problem from the last unit is a famous trap: with coin values 1, 5 and 10, the greedy rule (always take the biggest coin that fits) gives the optimal answer for 12 — but with coin values 1, 3 and 4, the greedy answer for 6 is 4 + 1 + 1 (three coins), while the optimal answer is 3 + 3 (two coins). The lesson is that a greedy algorithm needs a proof, not just an intuition. Before trusting one, ask: can the first greedy choice always be part of some optimal solution? If the answer is not clearly yes, reach for dynamic programming instead.

def activity_selection(activities):
    # activities: list of (start, finish); pick the most non-overlapping.
    ordered = sorted(activities, key=lambda a: a[1])
    chosen, last_finish = [], -1
    for start, finish in ordered:
        if start >= last_finish:
            chosen.append((start, finish))
            last_finish = finish
    return chosen


acts = [(1, 4), (3, 5), (0, 6), (5, 7), (8, 9), (5, 9)]
print(activity_selection(acts))  # [(1, 4), (5, 7), (8, 9)]

Union-Find: keeping track of groups

Many problems ask about connectivity: are these two nodes in the same group? How many groups are there? The Union-Find data structure (also called a disjoint-set union) answers those questions almost instantly. It keeps a parent pointer for each item; find follows the pointers to the group's representative, and union joins two groups by attaching one representative under the other. With two optimisations — path compression (flattening the pointers as you follow them) and union by size (attaching the smaller group under the larger) — each operation costs almost constant time, a complexity written as O(α(n)) where α is a function that grows so slowly it is effectively constant for any input you will ever meet.

Union-Find shines in problems such as Kruskal's algorithm for minimum spanning trees, counting connected components, and deciding whether adding an edge would create a cycle. The pattern is always the same: start with every item in its own group, then union items as you discover connections, and use find to test whether two items are already connected. It is a small structure — the code below fits in a few lines — but it is one of the highest-value tools in the competitive programmer's kit.

class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False  # already in the same group
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        return True


uf = UnionFind(5)
print(uf.union(0, 1))  # True — joined
print(uf.union(0, 1))  # False — already together
print(uf.find(0) == uf.find(1))  # True

Going further

Kruskal's algorithm is the classic application of Union-Find, and it is a greedy algorithm with a proof. To find the cheapest set of edges connecting all nodes — the minimum spanning tree — sort all the edges by weight, then add them one by one, skipping any edge whose ends are already connected (which Union-Find tells you instantly). The result is the cheapest possible connected network, and the proof is an exchange argument of the same kind as activity selection: the cheapest edge that does not form a cycle can always be part of some optimal tree. Kruskal's algorithm runs in O(E log E) time, dominated by the sort.

Another famous greedy algorithm is Huffman coding, which builds the most efficient prefix code for a set of symbols — the idea behind much of file compression. It repeatedly merges the two least frequent symbols into a combined node, building a tree from the leaves up, and the code for each symbol is the path from the root. Frequent symbols end up near the top of the tree with short codes; rare symbols get long ones. It is greedy, it is optimal, and it is a good example of how a simple local rule can produce a globally best result when the problem has the right structure.

Greedy algorithms are easy to believe and hard to prove, so practise the proof on the activity problem. Take any optimal solution that does not include the earliest-finishing activity, and swap its first activity for the earliest-finishing one. The swapped solution is still valid — the earliest-finishing activity ends no later than the one it replaced, so it cannot overlap anything the rest of the solution does — and it has the same number of activities, so it is still optimal. That swap is the exchange argument, and once you have carried it out yourself, the greedy rule stops being a guess and becomes a fact. Try the same argument on the coin problem with values 1, 3 and 4, and watch it fail — which is exactly how you discover that the greedy rule is wrong there.

Key Terms

Greedy algorithm
An algorithm that makes the best immediate choice at each step, never reconsidering.
Activity selection
Choosing the largest set of non-overlapping activities; solved greedily by earliest finish time.
Exchange argument
A proof technique: showing any optimal solution can be swapped to include the greedy choice.
Union-Find (disjoint-set union)
A data structure tracking which items are in the same group, with near-constant-time find and union.
find
The Union-Find operation returning the representative of an item's group.
union
The Union-Find operation merging two groups into one.
Path compression
Flattening parent pointers during find, so later finds are faster.
Kruskal's algorithm
A greedy algorithm building a minimum spanning tree by adding the cheapest edge that does not form a cycle.

Discussion Questions

  1. Why does the earliest-finish rule work for activity selection, but the biggest-coin rule fail for coin values 1, 3 and 4? What is different?
  2. Before trusting a greedy algorithm, what question should you ask? How would you test your answer?
  3. Union-Find answers 'are these two connected?' almost instantly. What problems could you solve with that question alone?

Practice Questions

  1. Trace activity selection on [(1, 4), (3, 5), (0, 6), (5, 7), (8, 9), (5, 9)]. Why is (3, 5) skipped?
  2. With coins 1, 3 and 4, what does greedy give for 6, and what is optimal?
  3. What does union(0, 1) return the second time it is called, and why?
  4. What two optimisations make Union-Find nearly constant-time?
  5. How would you use Union-Find to detect a cycle while adding edges one by one?
Show answers
  1. It starts at 3, before the chosen (1, 4) finishes at 4. Activities are considered in finish-time order; (3, 5) overlaps the already-chosen (1, 4).
  2. Greedy gives 4 + 1 + 1 (three coins); optimal is 3 + 3 (two coins). Greedy fails here, which is why a greedy algorithm needs a proof, not just intuition.
  3. False. 0 and 1 are already in the same group, so there is nothing to join.
  4. Path compression (or halving) and union by size. Together they keep the trees almost flat, so find is effectively O(1).
  5. Before adding an edge, check whether its ends are already in the same group. If find(u) == find(v), the edge would close a cycle; otherwise union them.
Keep reading to complete this lesson