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" with arguments[i] = [a, b]: join the component containing a with the component containing b (leaving the structure unchanged if a and b already share a component), then append the resulting total component count as an int.
  • "connected" with arguments[i] = [a, b]: append True if a and b currently belong to the same component, or False otherwise (bool).
  • "count" with arguments[i] = []: append the current total component count as an int.

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^5
  • 0 <= len(operations) == len(arguments) <= 2 * 10^5
  • Every entry in operations is "union", "connected", or "count".
  • Whenever operations[i] is "union" or "connected", n >= 1 and 0 <= a, b < n; whenever operations[i] is "count", arguments[i] is [].
  • Expected complexity: O(n + m * alpha(n)) time and O(n) auxiliary memory across m commands.

Step-by-step walkthrough

  1. Restate the problem and API

    We start with n isolated nodes labeled 0 through n - 1, so there are initially n separate connected components. We receive two parallel lists, operations and arguments, and must produce one output per operation in order:

    • "union" with [a, b]: merge a's component with b's component, then append the current number of components (int).
    • "connected" with [a, b]: append True if a and b belong to the same component, else False (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) is True). - Calling union(a, b) when a and b are already in the same component (including a == b) leaves the component count unchanged, and still appends that count.

  2. 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. Checking connected(a, b) is then just label[a] == label[b] in O(1) time, and count() is the number of distinct labels.

    The bottleneck is union(a, b): to merge two groups, you have to scan the entire label array of length n and overwrite every node carrying the old label. Over m unions, m scans of n nodes take O(m * n) steps—around 10^10 operations when n = 10^5 and m = 10^5. We need a way to merge two entire groups by changing one pointer instead of relabeling thousands of nodes.

  3. Key idea: represent each component as a rooted tree

    Instead of giving every node a flat group ID, give every node a parent pointer: - Initially parent[i] = i for every node 0..n-1: each node is the root (top leader) of its own one-node tree. - Each component has exactly one root r (satisfying parent[r] == r), which acts as that component's ID. - find(x) follows parent pointers upward until it hits the root. - connected(a, b) checks find(a) == find(b). - union(a, b) finds root_a = find(a) and root_b = find(b). If root_a != root_b, we set parent[root_b] = root_a (merging both trees in one pointer assignment!) and decrement a running counter self.components by 1.

    Start (n = 4, components = 4):    After union(0, 1) and union(2, 3) (components = 2):
      0    1    2    3                      0         2
                                            |         |
                                            1         3
    

    Because self.components starts at n and drops by 1 only when two distinct roots merge, count() is a single O(1) read.

  4. 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 -> 0 where find takes O(n) steps. Two classic optimizations prevent that completely:

    1. Union by rank: Store rank[r] for each root as an upper bound on its tree height (starting at 0). When merging root_a and root_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!)                                                        |
                                                                               4
    
    Because 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!).
    
    1. Path compression: Whenever find(x) climbs up to root, rewrite parent[x] = root for every node visited along the way:
    Before find(3):     After find(3):
          0                   0
          |                /  |  \
          1               1   2   3
          |
          2
          |
          3
    

    Together, union by rank and path compression make m operations run in O(m * α(n)) time, where α(n) <= 4 is the inverse Ackermann function—essentially O(1) per operation.

  5. Implement `UnionFind` and the stream driver

    Let's put UnionFind and process_union_find_operations together cleanly. Because union by rank bounds tree depth to <= log2(n), recursive find is completely safe from Python's recursion limit even on 10^6 nodes.

    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.components
    
  6. Walk through Example 1

    Let's trace n = 6 on ['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()        -> 3
    

    Forest at the end: {0, 2, 4} under root 0, {1, 5} under root 1, and {3} alone under root 3. Returned list: [6, 5, 4, 3, True, False, 3].

  7. 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 <= 4 for every realistic input size n. Initializing parent and rank scans n slots once (O(n)), each count reads self.components in O(1), and each union or connected runs at most two find calls in O(α(n)) amortized time.
  • Space: O(n) auxiliary space (plus O(m) for the returned results list). We store two flat lists (parent and rank) of length n and one integer counter; recursion depth inside find never exceeds log2(n) + 1.

Edge cases

  • Redundant or self unions (union(x, x) or union(a, b) when already connected): root_a == root_b, so union leaves self.components unchanged and the driver still appends the unchanged count.
  • Self connectivity (connected(x, x)): find(x) == find(x) always returns True.
  • Tiny graphs (n = 0 or n = 1) and empty streams (operations = []): n = 0 starts with components = 0; an empty operation list returns [].
  • Mixed return types: "connected" appends bool while "union" and "count" append int, preserving exact operation order.
  • Adversarial chain unions (union(i, i + 1) and union(i + 1, i) on 10^5 nodes): Union by rank keeps tree height <= 17 regardless of argument order, avoiding both O(n^2) slowdowns and Python recursion errors.

Common mistakes

  • Decrementing self.components unconditionally in union: Merging two nodes already in the same component (such as union(0, 2) in Example 2 or union(1, 1) in Example 3) must not reduce the component count.
  • Checking self.parent[a] == self.parent[b] instead of self.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] = b instead 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 by 1 only when rank[root_a] == rank[root_b]; incrementing unconditionally destroys the log2(n) height guarantee.
  • Scanning parent to count roots on every count() call: Counting i == parent[i] works, but takes O(n) per count() instead of O(1) with a running counter.

Alternative approaches

  • Union by size: Store size[root] (initialized to 1) instead of rank[root], always hang the smaller component under the larger one, and add size[root_b] into size[root_a]. This gives the exact same O(α(n)) amortized time and also answers component-size queries in O(1) once the root is found.
  • Iterative find with path halving: Instead of recursion, loop while self.parent[x] != x: self.parent[x] = self.parent[self.parent[x]]; x = self.parent[x], which achieves the same O(α(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 connected mutates self.parent during path compression, and two concurrent union calls can read the same roots, overwrite each other's parent link, or double-decrement self.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 for connected unless find skips 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] to root_a only when parent[root_b] == root_b. To prevent two threads from linking root_a -> root_b and root_b -> root_a simultaneously (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 decrement components only 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 per find), pushing a tuple (merged, root_b, root_a, old_rank_a) onto a history stack on every union. Calling undo() pops that record and, if merged is True, restores parent[root_b] = root_b, rank[root_a] = old_rank_a, and components += 1 in O(1) time.

Follow-up questions

Similar questions

More Motive interview questions

All 4 Motive questions →