Sub topic 1
The Problem: Grouping Elements and Asking Who Is Together
Prerequisites
This chapter assumes you are comfortable with:
- Python lists, index access, loops, and functions.
- Graph basics: nodes, edges, and what it means for two nodes to be connected.
- Big-O notation, enough to compare O(1), O(n), and O(n²).
The problem
You have n elements numbered 0 to n-1. At the start, each element is alone in its own group. Over time, groups merge. You need to answer one question again and again: are these two elements in the same group?
This is the disjoint set problem. "Disjoint" means every element belongs to exactly one set, and no set overlaps another. The structure that solves it is called union-find, or disjoint set union (DSU).
It supports two operations:
find(x)returns the representative of the set that contains x. The representative is one chosen member that names the set.union(a, b)merges the set containing a with the set containing b.
Two elements are together exactly when find(a) == find(b).
This is also called dynamic connectivity on a graph. Each union(a, b) is like adding an edge between a and b. Each query asks whether a path exists between two nodes, and the edges keep arriving.
A first attempt: one label per element
The simplest design stores a label for each element. Elements with the same label are in the same set.
class LabelSets:
def __init__(self, n):
self.label = list(range(n))
def find(self, x):
return self.label[x]
def union(self, a, b):
la, lb = self.label[a], self.label[b]
if la == lb:
return
for i in range(len(self.label)):
if self.label[i] == la:
self.label[i] = lb
sets = LabelSets(6)
sets.union(0, 1)
sets.union(2, 3)
sets.union(1, 3)
print(sets.find(0) == sets.find(2)) # True
print(sets.find(0) == sets.find(4)) # FalseThis is correct, and find is O(1). But union scans the whole array to relabel one set, so it costs O(n). Merging everything takes n-1 unions, which adds up to O(n²). For a million elements, that is far too slow.
Why not just search the graph?
You could store the edges and run a breadth-first search for each query. That costs O(V + E) per query, and it repeats work that earlier queries already did. Union-find keeps a compact summary of what is connected, so queries are cheap.
| Approach | find / query | union / add edge |
|---|---|---|
| Label array | O(1) | O(n) |
| Graph search per query | O(V + E) | O(1) |
| Union-find (later chapters) | nearly O(1) amortized | nearly O(1) amortized |
The next chapters build the third row. The idea is to store each set as a tree of parent pointers, so that a merge only changes one pointer instead of relabeling a whole set.
Common mistakes to avoid
- Treating the representative as permanent. After a union, the representative of a set can change, so never keep an old
findresult and compare it later. - Comparing elements directly. Always compare
find(a)withfind(b), notawithb. - Expecting to split a set. The problem only merges sets. Removing an element or splitting a set is outside this structure, and the last chapters return to this limit.
- Forgetting that a union of two elements already in one set changes nothing. A good implementation notices this, and the later cycle detection chapter depends on it.
Exercise
Starting from six singleton sets 0..5, you run union(0, 1), union(2, 3), union(4, 5), then union(1, 4). Using the label-array version above, how many sets remain, and does find(0) == find(5) hold?
Show answer
Three sets remain after the first three unions. The fourth union merges {0,1} with {4,5}, leaving {0,1,4,5} and {2,3}, so two sets remain. find(0) == find(5) is True because 0 and 5 are now in the same set.
Exercise
Why does the label-array version take O(n²) total time to merge n elements into one set, and what kind of change would fix it?
Show answer
Each union scans all n labels, and merging n elements needs n-1 unions, so the total is O(n²). The fix is to avoid relabeling every member, for example by storing each set as a tree of parent pointers so that a merge changes a single pointer.