Keep track of the components.
Merge connectivity groups efficiently without storing every path between vertices.
01 Model the idea
Disjoint-set union tracks a partition into nonoverlapping components. find returns a representative; union merges components if they differ. Path compression shortens future find paths, while union by size or rank prevents unnecessarily tall trees. The resulting near-constant amortised bound uses the inverse Ackermann function, but the structure does not itself tell you the actual route between vertices.
Each vertex belongs to exactly one representative component.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
FIND component representatives
IF distinct, attach the smaller tree to the larger
COMPRESS paths during later finds03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
class DSU:
def __init__(self, n): self.parent, self.size = list(range(n)), [1] * n
def find(self, x):
while x != self.parent[x]:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a, b):
a, b = self.find(a), self.find(b)
if a == b: return False
if self.size[a] < self.size[b]: a, b = b, a
self.parent[b] = a; self.size[a] += self.size[b]
return True
sets = DSU(4)
print(sets.union(0, 1), sets.union(1, 2), sets.union(0, 2))
print(sets.find(0) == sets.find(2))True True False True
- 1
The representatives are implementation details; callers should compare find results rather than expecting one particular id to remain the leader.
- 2
Path halving updates a parent to its grandparent while traversing. Union by size attaches the smaller component below the larger.
- 3
The structure supports connectivity under additions. Removing arbitrary edges requires a different strategy; ordinary DSU cannot reconstruct how a component should split.
04 Count the cost
Amortised O(α(V)) per operation with compression and size/rank
O(V)
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Count connected components after two successful merges among five vertices.
Reveal one possible solution +
parent = list(range(5))
def find(x):
while parent[x] != x: x = parent[x]
return x
components = 5
for a, b in [(0, 1), (1, 2)]:
a, b = find(a), find(b)
if a != b: parent[b] = a; components -= 1
print(components)06 Check your reasoning
What does DSU answer directly?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.