Sub topic 9
Tracking Components as Edges Arrive
This chapter assumes you have read the earlier union-find chapters. You should know what find and union do, and why path compression and union by size make each operation run in near-constant amortized time. It also assumes you can read Python classes and you know the BFS labeling approach from earlier in the tutorial.
Up to now, the graph was fixed before you started. Many real problems don't work that way. Network links come online one at a time, users befriend each other in a feed, and pixels get merged as a segmentation runs. After each new edge, you may be asked how many components exist, whether two vertices are connected, or how big the largest group has become. This setting is called incremental connectivity: edges are only ever added, and queries arrive in between the additions.
Why Re-Running a Traversal Is the Wrong Tool
The naive approach rebuilds the labels with BFS after every edge. Each rebuild costs O(V + E), so a stream of m edges costs O(m · (V + E)) in total. With a million vertices and a million edges, that is about 10¹² steps.
Union-find was designed for this pattern. Each new edge needs one union call, and that call also tells you whether the edge merged two components or landed inside one. You keep the component count as a running counter, so a count query costs O(1).
| Approach | Cost per added edge | Cost per "connected?" query | Supports edge deletion |
|---|---|---|---|
| Re-run BFS after each edge | O(V + E) | O(1) after relabeling | Yes, by re-running |
| BFS only when queried | O(1) to append to adjacency list | O(V + E) | Yes |
| Union-find with both optimizations | O(α(V)) amortized | O(α(V)) amortized | No |
Here α is the inverse Ackermann function from the previous chapter. It is at most 4 for any input you could store.
The Per-Edge Update
When an edge (u, v) arrives, there are only two outcomes:
find(u)andfind(v)return different roots. The edge joins two components, so the count drops by one and the new component's size is the sum of the two old sizes.- Both calls return the same root. The edge is redundant: u and v were already connected, so adding this edge closes a cycle. The count and all sizes stay the same.
The following class extends the union-find from earlier chapters with a running largest value. Then it processes a stream of edges and reports the state after each one.
class DisjointSet:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.components = n
self.largest = 1 if n > 0 else 0
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
self.largest = max(self.largest, self.size[ra])
return True
def connected(self, a, b):
return self.find(a) == self.find(b)
ds = DisjointSet(7)
stream = [(0, 1), (2, 3), (1, 2), (0, 3), (4, 5), (3, 4)]
for u, v in stream:
merged = ds.union(u, v)
status = "merged" if merged else "redundant"
print(f"{u}-{v}: {status}, components={ds.components}, largest={ds.largest}")
print(ds.connected(0, 5), ds.connected(0, 6))Output:
0-1: merged, components=6, largest=2
2-3: merged, components=5, largest=2
1-2: merged, components=4, largest=4
0-3: redundant, components=4, largest=4
4-5: merged, components=3, largest=4
3-4: merged, components=2, largest=6
True FalseVertex 6 never gets an edge, so it stays in a component by itself and keeps the final count at 2. Edge 0-3 is redundant because 0, 1, 2, and 3 were already joined through 0-1, 1-2, and 2-3.
Pattern: The Moment Everything Becomes Connected
A common question is: given timestamped links, at what time did the whole network first become one component? You sort the events by time, union them in that order, and stop as soon as the count reaches 1.
def earliest_full_connection(n, timed_edges):
ds = DisjointSet(n)
if ds.components == 1:
return 0
for t, u, v in sorted(timed_edges):
if ds.union(u, v) and ds.components == 1:
return t
return -1
logs = [(5, 0, 1), (1, 2, 3), (9, 1, 2), (3, 0, 1)]
print(earliest_full_connection(4, logs)) # 9The events at times 1 and 3 build {2, 3} and {0, 1}. The event at time 5 repeats 0-1 and changes nothing. The event at time 9 joins the two groups. The same loop structure, with edges sorted by weight instead of time, is the core of Kruskal's minimum spanning tree algorithm: Kruskal keeps exactly the edges for which union returns True.
The Big Limitation: Deletions
Union-find cannot split a set. Once two trees are merged, the structure has no record of which edge caused the merge, and path compression has already rewritten parent pointers. If edges can disappear, a plain disjoint set gives wrong answers.
There are three practical responses:
- All deletions known in advance (offline). Process the timeline backwards so that deletions become additions. This is shown below.
- Few deletions or rare queries. Rebuild with BFS when a deletion happens. That costs O(V + E) per rebuild, which is fine if rebuilds are uncommon.
- Fully dynamic, online. Specialized structures exist, such as Holm–de Lichtenberg–Thorup and link-cut trees for forests. They are complex and rarely worth building unless profiling shows you need them.
The Reverse-Time Trick
Suppose you start with all edges present and delete them in a known order, reporting the component count after each deletion. Played backwards, the process starts from the final graph and adds the deleted edges in reverse order. Union-find handles that direction well.
def components_after_deletions(n, edges, deletions):
deleted = set(deletions)
ds = DisjointSet(n)
for i, (u, v) in enumerate(edges):
if i not in deleted:
ds.union(u, v)
answers = []
for i in reversed(deletions):
answers.append(ds.components)
u, v = edges[i]
ds.union(u, v)
answers.reverse()
return answers
cycle = [(0, 1), (1, 2), (2, 3), (3, 0)]
print(components_after_deletions(4, cycle, [0, 2, 1])) # [1, 2, 3]The function records the count before re-adding each edge, because that count is the state just after the edge was deleted in forward time. Reversing the list at the end puts the answers back in forward order. Deleting edge 0 from the 4-cycle leaves a path, so the count is still 1. Deleting edge 2 splits the path into two pieces, and deleting edge 1 leaves {0, 3}, {1}, and {2}.
Gotchas in Real Streams
- Isolated vertices count. The counter starts at n, so every vertex must be registered up front. If the stream only names vertices as they appear in edges, a vertex that never appears is never counted.
- Unknown vertex IDs. When IDs are strings or arrive on the fly, replace the lists with dictionaries. Add an
add(x)method that createsparent[x] = xandsize[x] = 1and incrementscomponents, and call it the first time you see each ID. - Self-loops and duplicate edges. Both are handled correctly as redundant edges, because
find(u) == find(u). No special case is needed. - Recursion in
find. A recursivefindwithout union by size can build chains thousands of nodes long before compression flattens them, which crashes Python's recursion limit. The iterative two-passfindabove avoids that. - Concurrency.
findwrites to memory during path compression, so even read-only queries modify shared state. Guard the structure with a lock if several threads use it.
Choosing an Approach
| Situation | Recommended method |
|---|---|
| Graph fixed, answer needed once | BFS or iterative DFS labeling |
| Edges only added, queries interleaved | Union-find with a running count |
| Deletions known ahead of time | Union-find over the reversed timeline |
| Rare deletions, frequent additions | Union-find, with a BFS rebuild after each deletion |
| Frequent online insertions and deletions | Dynamic connectivity structure, or reconsider the problem |
Exercise
A stream adds edges (0,1), (1,2), (2,0), (3,4) to a graph with 5 vertices. For each edge, state whether union returns True or False, and give the component count after each step.
Show answer
(0,1) merges, count 4. (1,2) merges, count 3. (2,0) is redundant because 0 and 2 are already connected through 1, so the count stays 3. (3,4) merges, count 2. The final components are {0,1,2} and {3,4}.
Exercise
Why does componentsafterdeletions append ds.components before calling union, rather than after?
Show answer
In reverse time, the state before re-adding edge i is exactly the forward-time state right after edge i was deleted. Appending after the union would record the state before the deletion, which shifts every answer by one step.
Exercise
Modify the DisjointSet so it can also report how many redundant edges have arrived so far. What single change is needed, and what does that number mean for the graph?
Show answer
Add a counter initialized to 0 and increment it in union whenever ra == rb, before returning False. Each redundant edge closes a new independent cycle. The counter equals E − V + C, where C is the current component count. This is the cyclomatic number, the count of edges beyond a spanning forest.