Loading
Loading
Track which things are connected, with near-constant merges.
A disjoint-set structure maintains a collection of groups under two operations: find which group an element belongs to, and merge two groups. With path compression and union by rank both run in near-constant amortised time, which makes it the right tool when connectivity changes as you go.
Each set is a tree identified by its root. Path compression flattens the tree during lookups, so the structure gets faster the more it is queried.
The shape, not a solution. Adapt the condition and the state to the problem in front of you.
class UnionFind: def __init__(self, n): self.parent = list(range(n)) self.rank = [0] * n self.count = n # number of disjoint sets def find(self, x): # Path compression: re-point every node on the way to the root. while self.parent[x] != x: self.parent[x] = self.parent[self.parent[x]] x = self.parent[x] return x def union(self, a, b): root_a, root_b = self.find(a), self.find(b) if root_a == root_b: return False # already together; this edge closes a cycle # Union by rank keeps the trees shallow. if self.rank[root_a] < self.rank[root_b]: root_a, root_b = root_b, root_a self.parent[root_b] = root_a if self.rank[root_a] == self.rank[root_b]: self.rank[root_a] += 1 self.count -= 1 return True| Status | Problem | Difficulty | Role |
|---|---|---|---|
| Is There a Route?#95 | Easy | Primary | |
| Count the Reefs#97 | Medium | Related | |
| Study Circles#100 | Medium | Primary | |
Sign in to keep a note here. It is free, and nobody else can see it.
Sign in| Medium |
| Primary |
| Two-Team Split#104 | Medium | Related |