PrepStack · Markdown HTML

Union-Find dynamic connectivity

DSU, MST, and offline activation · HTML

Formal shape

Over objects V, process union(a,b), find(x), and connected(a,b); the relation is an equivalence relation and edges are insertion-only.

Recognition signals

False friends

SignalWhy it is different
A path or distance is requiredDSU discards internal paths; use BFS, Dijkstra, or an explicit graph.
Arbitrary online edge deletionPlain DSU cannot split a set; consider reverse-time processing, rollback DSU, or a dynamic-connectivity structure.

Core invariant

Each set is a parent-pointer tree with one representative root; size is meaningful only at roots.

State, transition, and processing order

ItemDefinition
StateParent pointers, root sizes, and an optional component counter.
Transitionfind compresses the path; union finds both roots and attaches the smaller tree under the larger.
Frontier / orderThere is no search frontier: processed relations are summarized by roots, while unprocessed operations remain in the stream.

Python skeleton

class DSU:
    def __init__(self, n):
        self.p = list(range(n))
        self.sz = [1] * n
        self.components = n
    def find(self, x):
        while x != self.p[x]:
            self.p[x] = self.p[self.p[x]]
            x = self.p[x]
        return x
    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a == b: return False
        if self.sz[a] < self.sz[b]: a, b = b, a
        self.p[b] = a
        self.sz[a] += self.sz[b]
        self.components -= 1
        return True
    def connected(self, a, b):
        return self.find(a) == self.find(b)

Correctness sketch

  1. Initially every object is a singleton, so the invariant holds.
  2. union links only distinct roots, exactly merging two equivalence classes.
  3. Path compression only redirects nodes to ancestors in the same tree, preserving membership.
  4. Induction over operations gives equal representatives exactly for connected objects.

Complexity

TimeSpaceParameters
O((n+m) α(n)) total for m operationsO(n)n objects, m operations, inverse-Ackermann function α

Edge cases

Error patterns

PatternWhy it fails / fix
Comparing parent entries directlyParents may not be roots; compare find results.
Linking ordinary nodesOnly roots should be linked, or sizes and tree depth become invalid.
Counting a duplicate mergeReturn immediately when both roots already match.

Selection and exclusion rules

RelationTemplateBoundary
implementation dependencyKruskal minimum spanning treeRejecting cycle-forming edges

Original micro-example

PartDetail
Result{0,1,3,4} becomes one component, 2 stays alone, and components=2.
ScenarioFive devices connect 0-1, 3-4, then 1-4.
WalkthroughThe first two links form separate trees; the third links their roots, making connected(0,3) true.

Recall prompts

My notes