Disjoint Set: Merge Nodes and Query Connectivity
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests ability to implement Union-Find with union by rank and path compression, supporting merge, connectivity, and component-count queries.
Disjoint Set: Merge Nodes and Query Connectivity
You have n nodes labeled 0 through n - 1, each initially its own isolated component. Your task is to build a data structure that efficiently handles three kinds of operations issued in sequence, then return the collected results.
Operations
| Name | Arguments | What to return |
|---|---|---|
"union" | [a, b] | the number of connected components after performing the union, whether or not a and b were already in the same component |
"connected" | [a, b] | True if a and b are in the same component, False otherwise |
"count" | [] | the current number of connected components |
Only these three operation names will appear. Every node index is guaranteed to be in range 0..n-1, and each operation is given the correct number of arguments.
Collect the return value of every operation into a list and return it.
Implementation Requirements
Your internal find routine must use path compression. Path halving — redirecting each visited node to its grandparent — is an accepted variant. Your union routine must apply union by rank: always attach the lower-rank root beneath the higher-rank root, and increment the rank only when two roots of equal rank are merged.
Constraints
0 <= n <= 10^41 <= len(operations) == len(arguments) <= 10^4- Each operation is one of
"union","connected","count" - For
"union"and"connected",arguments[i]contains exactly two integers, both in[0, n-1] - For
"count",arguments[i]is an empty list a == bis allowed; applying"union"to the same node twice is a no-op but still appends the current component countn = 0is valid;"count"returns0
Examples
Example 1
Input: run_component_queries(5, ['count', 'union', 'union', 'connected', 'union', 'connected', 'count'], [[], [0, 1], [1, 2], [0, 2], [3, 4], [2, 4], []])
Output: [5, 4, 3, True, 2, False, 2]
Example 2
Input: run_component_queries(4, ['connected', 'union', 'connected', 'union', 'union', 'connected'], [[0, 1], [0, 1], [0, 1], [1, 2], [2, 3], [0, 3]])
Output: [False, 3, True, 2, 1, True]
Example 3
Input: run_component_queries(1, ['count', 'union', 'connected'], [[], [0, 0], [0, 0]])
Output: [1, 1, True]
Hints
Hint 1
Track the number of components as a single integer. It starts at n and decreases by exactly 1 each time a union actually joins two previously separate components — a same-root union changes nothing but still appends the current count.
Hint 2
In your find routine, walk up the parent chain using path halving: set parent[x] = parent[parent[x]] before advancing x. This flattens the tree in a single pass without recursion, which also avoids Python's recursion limit on long chains.
Hint 3
For union by rank, compare the ranks of the two roots. Attach the smaller-rank root under the larger-rank root. Only when both ranks are equal do you increment the surviving root's rank by 1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem maps directly onto a Union-Find (Disjoint Set Union) data structure. The core idea is to represent each connected component as a tree, where every node holds a pointer to its parent and the root of each tree serves as the canonical identifier for its component.
State
Three things need to be tracked:
parent[i]— the parent of nodei. Initially every node is its own parent (each is a root).rank[i]— an upper bound on the height of the subtree rooted ati. Starts at 0 everywhere.components— the number of distinct components. Starts atnand decreases by 1 each time a union actually joins two separate roots.
find with path halving
To locate the root of any node, walk up the parent chain until reaching a node that points to itself. Along the way, apply path halving: set parent[x] = parent[parent[x]] before advancing x. Each visited node skips over its parent and points directly to its grandparent. This flattens the tree incrementally without a second pass or recursion, keeping Python's call stack safe on large inputs.
union with union by rank
When unioning nodes a and b, find their roots ra and rb. If they are already the same root, the nodes are already connected — just append the unchanged count. If they differ, attach the lower-rank root beneath the higher-rank root. This prevents trees from growing unnecessarily tall. The rank of the surviving root increases by 1 only when two roots of equal rank are joined. After a successful union, decrement components.
Why it is correct
The invariant is: every component is exactly one tree, and its root is the unique node where parent[root] == root. At initialization every node satisfies this trivially. A union between two distinct roots links one tree under the other, preserving the invariant. Path halving only redirects a node to another ancestor in the same tree, so it never changes which root a node belongs to.
The component counter stays accurate because it decreases by exactly 1 per successful cross-root union and never changes for a same-root union.
Complexity
- Time: amortized O(α(n)) per
find,union, orconnectedoperation, where α is the inverse Ackermann function. In practice α(n) ≤ 4 for any realistic n, so each operation is effectively constant.countis O(1). Total for m operations: O(n + m · α(n)). - Space: O(n) for
parentandrank. The iterative find uses O(1) extra space. Output takes O(m).
Edge cases
union(a, a)or repeated unions of already-connected nodes: roots are equal, so nothing changes, but the current count is still appended.n = 0: arrays are empty,components = 0, onlycountqueries (returning 0) are meaningful.n = 1: one node, one component; anyunion(0, 0)is a no-op.- Everything merged:
componentsreaches 1 and stays there.
from typing import List
def run_component_queries(n: int, operations: List[str], arguments: List[List[int]]) -> List[object]:
parent = list(range(n))
rank = [0] * n
components = n
def find(x):
# Path halving: redirect each node to its grandparent while walking up
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
result = []
for operation, args in zip(operations, arguments):
if operation == "union":
a, b = args
ra = find(a)
rb = find(b)
if ra != rb:
# Union by rank: attach lower-rank root under higher-rank root
if rank[ra] < rank[rb]:
ra, rb = rb, ra
parent[rb] = ra
if rank[ra] == rank[rb]:
rank[ra] += 1
components -= 1
result.append(components)
elif operation == "connected":
a, b = args
result.append(find(a) == find(b))
elif operation == "count":
result.append(components)
return result