Sub topic 14
Limitations: No Splitting, No Listing Members Cheaply
This chapter assumes you have the DisjointSet class from the earlier chapters (parent array, union by size, path compression) and know Big-O notation and basic graph connectivity. It covers what union-find cannot do, and what to use in those cases.
What the structure gives up
Union-find is fast because it stores very little: one parent pointer and one size per element. It does not store which elements are in a set, how they were connected, or in what order. Each limitation below follows from that.
No splitting
Union only merges sets. Nothing in the structure can undo a merge.
Suppose you union 0 with 1 and 1 with 2, then want to delete the edge between 0 and 1. The parent pointers don't record which edge caused which link. Path compression makes this worse, because it rewrites pointers so that node 2 may point straight at the root and no trace of the path remains.
If your problem involves deleting edges, you have these options:
- Process the operations in reverse. If you know all operations in advance (offline), run them backward so that deletions become unions.
- Use rollback union-find. It undoes the most recent unions in last-in, first-out order. It requires skipping path compression, so each find costs O(log n).
- Use a dynamic connectivity structure. Offline divide and conquer or link-cut trees handle arbitrary deletions, at higher cost and complexity.
- Recompute. For occasional deletions on a small graph, rebuilding with a graph search may be simpler.
No cheap member listing
find answers "which set is this element in?" but not "who else is in it?". With only parent pointers, listing a set means scanning every element and comparing roots:
def members_of(ds, x):
root = ds.find(x)
return [i for i in range(len(ds.parent)) if ds.find(i) == root]This takes O(n) time, no matter how small the set is. If you need member lists often, store them and merge the smaller list into the larger one on each union. Each element moves at most log n times, so the total merging cost is O(n log n).
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
class ListedDisjointSet(DisjointSet):
def __init__(self, n):
super().__init__(n)
self.members = [[i] for i in range(n)]
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.members[ra].extend(self.members[rb])
self.members[rb] = []
return super().union(a, b)
ds = ListedDisjointSet(6)
ds.union(0, 1)
ds.union(2, 3)
ds.union(1, 3)
print(sorted(ds.members[ds.find(0)])) # [0, 1, 2, 3]The cost is extra memory and more work per union. Add it only if you need it.
Other limits
- Elements are integers 0 to n-1. For strings or other objects, map them to indexes with a dictionary first.
- It answers connected or not, nothing more. It cannot return a path between two elements or a shortest distance. Use BFS or Dijkstra for those.
- It models undirected connectivity. Reachability in a directed graph is not symmetric, so union-find does not apply. Strongly connected components need a different algorithm.
- The set count only goes down.
countcan fall but never rise.
Choosing a tool
Exercise
You get a list of edges added to a graph and later a list of edges removed, and you must report the number of connected components after all removals. Why can't you apply union directly to each removal, and how can union-find still solve it?
Show answer
Union-find cannot split sets, so removals cannot be applied. Because all operations are known in advance, build the final graph (all edges minus the removed ones) with unions, then count the components with count. To get the count after each removal, process the removals in reverse order, adding each removed edge back with a union and recording count as you go.