Disjoint-Set Operations with Component Counting
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
A graph starts with n isolated vertices indexed 0 through n - 1 and zero edges, so every vertex initially forms its own separate component (n components overall).
Build a disjoint-set forest backed by rank-based merging and path flattening, and drive it from process_union_find_operations(n: int, operations: List[str], arguments: List[List[int]]) -> List[object]. Step through operations and arguments in parallel and record one output element per command:
"union"witharguments[i] = [a, b]: join the component containingawith the component containingb(leaving the structure unchanged ifaandbalready share a component), then append the resulting total component count as anint."connected"witharguments[i] = [a, b]: appendTrueifaandbcurrently belong to the same component, orFalseotherwise (bool)."count"witharguments[i] = []: append the current total component count as anint.
Examples
Example 1
Input:
n = 6
operations = ["count", "union", "union", "union", "connected", "connected", "count"]
arguments = [[], [0, 2], [2, 4], [1, 5], [0, 4], [4, 5], []]
Output: [6, 5, 4, 3, True, False, 3]
Walk-through:
- Initially all 6 vertices are separate (count -> 6).
- union(0, 2) forms {0, 2} (5 components), union(2, 4) expands it to {0, 2, 4} (4 components), and union(1, 5) forms {1, 5} while {3} remains alone (3 components).
- connected(0, 4) is True (both sit in {0, 2, 4}), connected(4, 5) is False, and the final count returns 3.
Example 2
Input:
n = 3
operations = ["connected", "union", "union", "connected", "union"]
arguments = [[0, 2], [0, 1], [1, 2], [0, 2], [0, 2]]
Output: [False, 2, 1, True, 1]
Walk-through: 0 and 2 start disconnected (False). Merging (0, 1) drops the count to 2, and merging (1, 2) unites all three vertices into {0, 1, 2} (1 component), so connected(0, 2) becomes True. The final union(0, 2) is redundant, so the count stays 1.
Example 3
Input:
n = 2
operations = ["union", "connected", "connected", "count"]
arguments = [[1, 1], [1, 1], [0, 1], []]
Output: [2, True, False, 2]
Walk-through: Calling union(1, 1) merges vertex 1 with itself, leaving 2 components. Every vertex is connected to itself (True), 0 and 1 are still separate (False), and count remains 2.
Constraints
0 <= n <= 10^50 <= len(operations) == len(arguments) <= 2 * 10^5- Every entry in
operationsis"union","connected", or"count". - Whenever
operations[i]is"union"or"connected",n >= 1and0 <= a, b < n; wheneveroperations[i]is"count",arguments[i]is[]. - Expected complexity:
O(n + m * alpha(n))time andO(n)auxiliary memory acrossmcommands.
Step-by-step walkthrough
Restate the problem and API
We start with
nisolated nodes labeled0throughn - 1, so there are initiallynseparate connected components. We receive two parallel lists,operationsandarguments, and must produce one output per operation in order:"union"with[a, b]: mergea's component withb's component, then append the current number of components (int)."connected"with[a, b]: appendTrueifaandbbelong to the same component, elseFalse(bool)."count"with[]: append the current number of components (int).
Two subtle cases show up right in Example 3 (
n = 2,union(1, 1),connected(1, 1)): - Every node is always connected to itself (connected(x, x)isTrue). - Callingunion(a, b)whenaandbare already in the same component (includinga == b) leaves the component count unchanged, and still appends that count.Why flat group labels are too slow
A tempting first attempt is an array
label = [0, 1, ..., n - 1]storing a group number for each node. Checkingconnected(a, b)is then justlabel[a] == label[b]inO(1)time, andcount()is the number of distinct labels.The bottleneck is
union(a, b): to merge two groups, you have to scan the entirelabelarray of lengthnand overwrite every node carrying the old label. Overmunions,mscans ofnnodes takeO(m * n)steps—around10^10operations whenn = 10^5andm = 10^5. We need a way to merge two entire groups by changing one pointer instead of relabeling thousands of nodes.Key idea: represent each component as a rooted tree
Instead of giving every node a flat group ID, give every node a
parentpointer: - Initiallyparent[i] = ifor every node0..n-1: each node is the root (top leader) of its own one-node tree. - Each component has exactly one rootr(satisfyingparent[r] == r), which acts as that component's ID. -find(x)followsparentpointers upward until it hits the root. -connected(a, b)checksfind(a) == find(b). -union(a, b)findsroot_a = find(a)androot_b = find(b). Ifroot_a != root_b, we setparent[root_b] = root_a(merging both trees in one pointer assignment!) and decrement a running counterself.componentsby1.Start (n = 4, components = 4): After union(0, 1) and union(2, 3) (components = 2): 0 1 2 3 0 2 | | 1 3Because
self.componentsstarts atnand drops by1only when two distinct roots merge,count()is a singleO(1)read.Keep trees flat with union by rank and path compression
If we link roots carelessly—for instance, hanging a tall tree under a single node over and over—the tree can degenerate into a long chain
n - 1 -> ... -> 1 -> 0wherefindtakesO(n)steps. Two classic optimizations prevent that completely:- Union by rank: Store
rank[r]for each root as an upper bound on its tree height (starting at0). When mergingroot_aandroot_b, always attach the smaller-rank root under the larger-rank root. Notice why the new root's height only increases when both trees had the exact same rank:
Unequal ranks (rank[0]=1, rank[2]=0): Equal ranks (rank[0]=1, rank[3]=1): 0 2 --> 0 0 3 --> 0 (rank becomes 2) | / \ | | / \ 1 1 2 1 4 1 3 (height stays 1!) | 4Because rank only rises by `1` when two trees of equal rank merge (at least doubling the node count), a root of rank `r` contains at least `2^r` nodes, guaranteeing height `<= log2(n)` (at most `16` for `100,000` nodes!).- Path compression: Whenever
find(x)climbs up toroot, rewriteparent[x] = rootfor every node visited along the way:
Before find(3): After find(3): 0 0 | / | \ 1 1 2 3 | 2 | 3Together, union by rank and path compression make
moperations run inO(m * α(n))time, whereα(n) <= 4is the inverse Ackermann function—essentiallyO(1)per operation.- Union by rank: Store
Implement `UnionFind` and the stream driver
Let's put
UnionFindandprocess_union_find_operationstogether cleanly. Because union by rank bounds tree depth to<= log2(n), recursivefindis completely safe from Python's recursion limit even on10^6nodes.class UnionFind: def __init__(self, n: int): self.parent = list(range(n)) self.rank = [0] * n self.components = n def find(self, x: int) -> int: if self.parent[x] != x: self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, a: int, b: int) -> bool: root_a = self.find(a) root_b = self.find(b) if root_a == root_b: return False 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.components -= 1 return True def connected(self, a: int, b: int) -> bool: return self.find(a) == self.find(b) def count(self) -> int: return self.componentsWalk through Example 1
Let's trace
n = 6on['count', 'union', 'union', 'union', 'connected', 'connected', 'count']with arguments[[], [0, 2], [2, 4], [1, 5], [0, 4], [4, 5], []]:Initial: parent = [0, 1, 2, 3, 4, 5], rank = [0, 0, 0, 0, 0, 0], components = 6 1. count() -> 6 2. union(0, 2) roots 0 & 2 tie (rank 0): parent[2] = 0, rank[0] = 1, components = 5 -> 5 3. union(2, 4) find(2)=0 (rank 1) > root 4 (rank 0): parent[4] = 0, components = 4 -> 4 4. union(1, 5) roots 1 & 5 tie (rank 0): parent[5] = 1, rank[1] = 1, components = 3 -> 3 5. connected(0,4) find(0) == 0 and find(4) == 0 -> True 6. connected(4,5) find(4) == 0 != find(5) == 1 -> False 7. count() -> 3Forest at the end:
{0, 2, 4}under root0,{1, 5}under root1, and{3}alone under root3. Returned list:[6, 5, 4, 3, True, False, 3].Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple class UnionFind: def __init__(self, n: int): # parent: list of length n where parent[i] is node i's parent in the forest; # parent[r] == r marks r as the root (representative) of its component. # Initially for n = 4: parent = [0, 1, 2, 3]. self.parent = list(range(n)) # rank: list of length n where rank[r] is an upper bound on the height of root r's tree. # Initially every one-node tree has height 0: rank = [0, 0, ..., 0]. self.rank = [0] * n # components: running count of distinct connected components (starts at n solo nodes). self.components = n def find(self, x: int) -> int: # Walk parent links until reaching the root (where parent[root] == root). if self.parent[x] != x: # Path compression: rewire x directly to its root on the way back up # so future find calls on x (and its descendants) finish in one hop. self.parent[x] = self.find(self.parent[x]) return self.parent[x] def union(self, a: int, b: int) -> bool: root_a = self.find(a) root_b = self.find(b) # If a and b already share the same root, they are already in one component: # do not relink and do not decrement self.components! if root_a == root_b: return False # Union by rank: ensure root_a has the >= rank so we always hang the # shorter tree (root_b) under the taller root (root_a). if self.rank[root_a] < self.rank[root_b]: root_a, root_b = root_b, root_a self.parent[root_b] = root_a # Tree height can only grow by 1 when two trees of equal rank are merged. if self.rank[root_a] == self.rank[root_b]: self.rank[root_a] += 1 # Two separate components just merged into one, reducing the total count by 1. self.components -= 1 return True def connected(self, a: int, b: int) -> bool: # Two nodes are in the same component if and only if their trees have the same root. return self.find(a) == self.find(b) def count(self) -> int: return self.components def process_union_find_operations(n: int, operations: List[str], arguments: List[List[int]]) -> List[object]: uf = UnionFind(n) # results: mixed list of bools (for "connected") and ints (for "union" and "count"). results: List[object] = [] # Process each streamed operation alongside its argument list in lockstep. for op, args in zip(operations, arguments): if op == "union": uf.union(args[0], args[1]) # Report the updated component count after every union, even if no merge happened. results.append(uf.count()) elif op == "connected": results.append(uf.connected(args[0], args[1])) elif op == "count": results.append(uf.count()) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine n people at a conference who start out in n solo groups, each wearing their own name as group leader. When two groups merge, making everyone in one group reprint their badges would take forever—instead, the leader of one group simply writes down the name of the other group's leader! To check if two people belong to the same connected component (a maximal group of nodes reachable from one another), both follow leader pointers up to their top boss (root or representative, where parent[r] == r) and check whether they land on the same person.
A naive flat-label array makes connected fast (O(1)), but every union must scan all n nodes to relabel an entire group, costing O(m * n) time across m operations. On the other hand, linking trees naively without balancing can create a single chain of n nodes where following parent pointers takes O(n) steps per query.
A Disjoint Set Union (Union-Find)—a data structure that maintains non-overlapping sets under fast merges and group lookups—solves both problems with two rules: union by rank (always hanging the shorter tree under the root of the taller tree so height stays <= log2(n)) and path compression (rewiring every node visited during find(x) directly to the root). Let's trace n = 6 from Example 1 (parent = [0, 1, 2, 3, 4, 5], rank = [0, 0, 0, 0, 0, 0], components = 6):
- union(0, 2): roots 0 and 2 both have rank 0, so 2 attaches under 0, rank[0] becomes 1, and components drops to 5.
- union(2, 4): find(2) returns root 0 (rank 1), while root 4 has rank 0; 4 attaches under 0, rank[0] stays 1, and components drops to 4.
- union(1, 5): roots 1 and 5 merge under 1, dropping components to 3, so connected(0, 4) returns True (both root at 0) while connected(4, 5) returns False (0 != 1).
Complexity
Let n be the number of nodes and m be the number of operations in operations.
- Time: O(n + m * α(n)) amortized, where amortized time means the guaranteed average cost per operation across the full sequence, and
α(n)(the inverse Ackermann function) is an extraordinarily slow-growing function that stays<= 4for every realistic input sizen. Initializingparentandrankscansnslots once (O(n)), eachcountreadsself.componentsinO(1), and eachunionorconnectedruns at most twofindcalls inO(α(n))amortized time. - Space: O(n) auxiliary space (plus
O(m)for the returnedresultslist). We store two flat lists (parentandrank) of lengthnand one integer counter; recursion depth insidefindnever exceedslog2(n) + 1.
Edge cases
- Redundant or self unions (
union(x, x)orunion(a, b)when already connected):root_a == root_b, sounionleavesself.componentsunchanged and the driver still appends the unchanged count. - Self connectivity (
connected(x, x)):find(x) == find(x)always returnsTrue. - Tiny graphs (
n = 0orn = 1) and empty streams (operations = []):n = 0starts withcomponents = 0; an empty operation list returns[]. - Mixed return types:
"connected"appendsboolwhile"union"and"count"appendint, preserving exact operation order. - Adversarial chain unions (
union(i, i + 1)andunion(i + 1, i)on10^5nodes): Union by rank keeps tree height<= 17regardless of argument order, avoiding bothO(n^2)slowdowns and Python recursion errors.
Common mistakes
- Decrementing
self.componentsunconditionally inunion: Merging two nodes already in the same component (such asunion(0, 2)in Example 2 orunion(1, 1)in Example 3) must not reduce the component count. - Checking
self.parent[a] == self.parent[b]instead ofself.find(a) == self.find(b): Two nodes in the same component can still have different immediate parents before path compression visits both of them. - Linking
self.parent[a] = binstead of linking roots (self.parent[root_b] = root_a): Overwriting a non-root node's parent detaches it from its old ancestors and splits an existing component! - Incrementing
rank[root_a]on every merge: Rank should increase by1only whenrank[root_a] == rank[root_b]; incrementing unconditionally destroys thelog2(n)height guarantee. - Scanning
parentto count roots on everycount()call: Countingi == parent[i]works, but takesO(n)percount()instead ofO(1)with a running counter.
Alternative approaches
- Union by size: Store
size[root](initialized to1) instead ofrank[root], always hang the smaller component under the larger one, and addsize[root_b]intosize[root_a]. This gives the exact sameO(α(n))amortized time and also answers component-size queries inO(1)once the root is found. - Iterative
findwith path halving: Instead of recursion, loopwhile self.parent[x] != x: self.parent[x] = self.parent[self.parent[x]]; x = self.parent[x], which achieves the sameO(α(n))bound with zero call-stack frames.
Follow-up questions
- Is this data structure safe for concurrent threads, and how would you synchronize it? No: even
connectedmutatesself.parentduring path compression, and two concurrentunioncalls can read the same roots, overwrite each other's parent link, or double-decrementself.components(Python's GIL can switch threads between bytecodes inside a method). The cleanest practical fix is wrapping public methods with a mutex (a mutual-exclusion lock that lets only one thread enter at a time), which holds the lock for just a few array lookups per call. Note that a readers-writer lock is not safe forconnectedunlessfindskips path compression during read-only queries! - How can a disjoint-set structure be implemented without locks across multiple CPU cores? Use compare-and-swap (CAS)—a hardware atomic instruction that updates a memory slot only if it still holds an expected old value—to link
parent[root_b]toroot_aonly whenparent[root_b] == root_b. To prevent two threads from linkingroot_a -> root_bandroot_b -> root_asimultaneously (creating a cycle!), break ties with a fixed total order such as always linking the higher root ID under the lower root ID (or random per-node priorities), and atomically decrementcomponentsonly in the thread whose CAS succeeded. - How would you extend the structure to support an undo() operation that reverts the latest merge? Drop path compression and keep union by rank alone (
O(log n)worst-case perfind), pushing a tuple(merged, root_b, root_a, old_rank_a)onto a history stack on everyunion. Callingundo()pops that record and, ifmergedisTrue, restoresparent[root_b] = root_b,rank[root_a] = old_rank_a, andcomponents += 1inO(1)time.
Follow-up questions
- Is this data structure safe for concurrent threads, and how would you synchronize it?
- How can a disjoint-set structure be implemented without locks across multiple CPU cores?
- How would you extend the structure to support an undo() operation that reverts the latest merge?
Similar questions
- Undirected Connectivity Queries via Disjoint Sets
- Live Courier Tracking and Dispatch Platform
- Resilient Paginated REST Ingestion and Aggregation
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses