Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Connect everything cheaply
EXPERIMENT 44 / 66

Keep track of the components.

Merge connectivity groups efficiently without storing every path between vertices.

BY NAVAN SAMI◷ 10 MIN READSTRETCHSTRUCTURE

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.

THE THING THAT MUST STAY TRUE

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.

the_strategy.txt
FIND component representatives
IF distinct, attach the smaller tree to the larger
COMPRESS paths during later finds

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

union_find.py
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))
↳ EXPECTED OUTPUT
True True False
True
  1. 1

    The representatives are implementation details; callers should compare find results rather than expecting one particular id to remain the leader.

  2. 2

    Path halving updates a parent to its grandparent while traversing. Union by size attaches the smaller component below the larger.

  3. 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

TIME

Amortised O(α(V)) per operation with compression and size/rank

SPACE

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

A SMALL MISSION

Count connected components after two successful merges among five vertices.

Reveal one possible solution +
one_possible_solution.py
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

QUICK SIGNAL CHECK

What does DSU answer directly?

ANOTHER PATTERN IN YOUR TOOLKIT.

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.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.