Sub topic 9
Tracking Components as Edges Arrive
This chapter assumes you have read the earlier chapters on BFS labeling and on union-find with path compression and union by size. It also assumes you can read Big-O notation.
The Problem with Recomputing
In many real systems the graph is not fixed. Edges arrive one at a time: a friendship is accepted, a network cable is plugged in, two accounts are found to share a payment card. After each arrival you may need to answer questions like these:
- How many components exist right now?
- Are vertices
aandbconnected yet? - Did this edge join two groups, or did it land inside one group that already existed?
You could rerun BFS after every new edge. With E edges, that costs O(E · (V + E)) in total, which is quadratic. Union-find handles each edge in nearly constant amortized time, so the whole stream costs O(E · α(V)), where α is the inverse Ackermann function. α(V) is at most 4 for any graph you will meet in practice.
| Approach | Cost per new edge | Total for E edges | Answers "connected?" |
|---|---|---|---|
| Rerun BFS each time | O(V + E) | O(E · (V + E)) | O(1) after labeling |
| Union-find | O(α(V)) amortized | O(E · α(V)) | O(α(V)) |
How Each Edge Is Processed
Each arriving edge goes through the same short decision.
The return value of union carries useful information. True means two components merged. False means the edge closes a cycle. Cycle detection works this way in Kruskal's minimum spanning tree algorithm.
A Streaming Tracker
The code below reuses the DisjointSet class from the previous chapter and records the state after every edge. It also reports the moment the graph first becomes fully connected.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.components = n
def find(self, x):
root = x
while self.parent[root] != root:
root = self.parent[root]
while self.parent[x] != root:
nxt = self.parent[x]
self.parent[x] = root
x = nxt
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.components -= 1
return True
def track_stream(n, edges):
ds = DisjointSet(n)
fully_connected_at = None
for step, (u, v) in enumerate(edges, start=1):
merged = ds.union(u, v)
status = "merged" if merged else "redundant"
print(f"step {step}: edge ({u}, {v}) {status}, components = {ds.components}")
if ds.components == 1 and fully_connected_at is None:
fully_connected_at = step
return ds, fully_connected_at
edges = [(0, 1), (2, 3), (1, 2), (0, 3), (4, 5), (3, 4)]
ds, when = track_stream(6, edges)
print("fully connected after step:", when)
print("0 and 5 connected?", ds.find(0) == ds.find(5))Output:
step 1: edge (0, 1) merged, components = 5
step 2: edge (2, 3) merged, components = 4
step 3: edge (1, 2) merged, components = 3
step 4: edge (0, 3) redundant, components = 3
step 5: edge (4, 5) merged, components = 2
step 6: edge (3, 4) merged, components = 1
fully connected after step: 6
0 and 5 connected? TrueYou can call find between arrivals at any time, so the structure answers connectivity queries that are interleaved with updates.
Common Mistakes
- Decrementing the count unconditionally. If you subtract one on every edge, redundant edges and self-loops like
(2, 2)push the count too low. Decrement only when the two roots differ. - Comparing vertices instead of roots.
ds.parent[a] == ds.parent[b]is not a connectivity test. Always comparefind(a)withfind(b). - Expecting deletions to work. Union-find can merge sets but cannot split them.
Exercises
Exercise
With 5 vertices and the edge stream (0, 1), (1, 2), (0, 2), (3, 4), (2, 3), what is the component count after each edge, which edge is redundant, and at which step does the graph become fully connected?
Show answer
The counts are 4, 3, 3, 2, 1. Edge (0, 2) is redundant because 0 and 2 are already joined through 1. The graph becomes fully connected at step 5, when edge (2, 3) arrives.
Exercise
Why can't you support edge deletion by simply resetting parent[x] = x for one endpoint?
Show answer
Path compression and union by size flatten the trees, so a tree's shape no longer matches the edges that built it. Other vertices may point to x or through x. Some of them may still be connected to the rest of the set by other edges, and others may not. Resetting one pointer cannot tell these cases apart, so the sets become wrong.