Sub topic 9
Counting Connected Components
This chapter assumes you know the DisjointSet class from the earlier chapters, with find, union, and union by size plus path compression. It also assumes you know what a connected component is: a maximal group of vertices where every pair is joined by some path.
The idea: one counter
Start with n elements. Each one is its own set, so there are n components. Every union that merges two different sets reduces the number of components by exactly one. A union that finds both elements already in the same set changes nothing.
So you don't need to scan the structure to count components. You keep a counter, start it at n, and decrement it only when a union succeeds. The count field in the class does this, and union returns True only when it merges two sets.
The decision inside union
Worked example
The class below is the one from earlier chapters, repeated so this example runs on its own. The function feeds a list of edges into it and records the component count after each edge.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.count = n
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root:
self.parent[x], x = root, self.parent[x]
return root
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
self.count -= 1
return True
def components_after_each_edge(n, edges):
ds = DisjointSet(n)
history = []
for u, v in edges:
ds.union(u, v)
history.append(ds.count)
return history
print(components_after_each_edge(6, [(0, 1), (2, 3), (1, 3), (0, 2)]))
# [5, 4, 3, 3]Here is how the count changes:
| Edge | Effect | Components |
|---|---|---|
| start | six singletons | 6 |
| (0, 1) | merges {0} and {1} | 5 |
| (2, 3) | merges {2} and {3} | 4 |
| (1, 3) | merges {0,1} and {2,3} | 3 |
| (0, 2) | already together, no merge | 3 |
The last edge is redundant for connectivity. It would close a cycle, which the next chapter uses.
Why this beats a graph search
A depth-first search can also count components, but it needs the whole graph in memory and must be rerun if edges change. Union-find handles edges as they arrive. After each edge you can read ds.count in constant time, and each edge costs nearly constant amortized time. This is the dynamic connectivity setting, where edges are only added.
Union-find is a good fit when:
- Edges arrive as a stream or a list and you want the count after each one.
- You only need the number of components, not the vertices in each one.
- Elements can be mapped to indices
0ton - 1. For other labels, such as strings, map each one to an index with a dictionary first.
Common mistakes
- Forgetting isolated vertices. The count starts at
n, not at the number of vertices that appear in edges. A vertex with no edges is its own component. - Counting roots by hand with stale data. If you count elements where
parent[i] == i, that works. Counting distinct values ofparent[i]without callingfinddoes not, because parents may not be roots. - Expecting counts to go up. Union-find cannot split sets, so the count never increases. To handle edge deletions, see the limitations chapter.
Exercise
A graph has 10 vertices and 7 edges. You feed all the edges into a DisjointSet(10). If every union call returns True, what is ds.count at the end? If exactly two calls returned False, what is it?
Show answer
If all 7 unions succeed, each lowers the count by one, so the count is 10 - 7 = 3. If two calls returned False, only 5 merges happened, so the count is 10 - 5 = 5.
Exercise
Why is it wrong to write self.count -= 1 at the top of union, before the roots are compared?
Show answer
It would decrement the count even when both elements are already in the same set, so the count would drop below the true number of components.