Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Disjoint Set Union itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Disjoint Set Union tracks component membership through representative roots. Correctness comes from comparing and joining roots; path compression and union by size only shorten future searches without changing the partition.
1 practice exercise3 interview problems
Recognize it when Undirected connectivity is queried while edges are added.
Checking your account…
Disjoint Set Union maintains a partition of nodes into non-overlapping components. Each component is
represented by one root; two nodes are connected exactly when find returns the same root.
Initially every node is its own parent. Only roots may become children during union. Parent pointers encode membership, while root size or rank guides which representative remains.
find follows parents to a root, then rewrites visited parents toward that root. Compression changes
shape but never component membership.
def compress_all(parent):
compressed = parent.copy()
def find(node):
if compressed[node] != node:
compressed[node] = find(compressed[node])
return compressed[node]
roots = [find(node) for node in range(len(compressed))]
return roots, compressedImplement compress_all(parent). Return roots for every node and a copied parent array compressed directly to roots. parent is a valid self-rooted acyclic forest: all parent indices are in range and every chain ends at a node that is its own parent.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def compress_all(parent):
compressed = parent.copy()
def find(node):
if compressed[node] != node:
compressed[node] = find(compressed[node])
return compressed[node]
roots = [find(node) for node in range(len(compressed))]
return roots, compressedAttach the smaller root below the larger and update size only at the surviving root. With path compression, a sequence of operations has inverse-Ackermann amortized time, effectively constant for interview-scale inputs.
def disjoint_set_trace(node_count, operations):
parent = list(range(node_count))
size = [1] * node_count
def find(node):
while parent[node] != node:
parent[node] = parent[parent[node]]
node = parent[node]
return node
results = []
for operation, left, right in operations:
left_root, right_root = find(left), find(right)
if operation == 'connected':
results.append(left_root == right_root)
elif left_root != right_root:
if size[left_root] < size[right_root]:
left_root, right_root = right_root, left_root
parent[right_root] = left_root
size[left_root] += size[right_root]
return resultsImplement disjoint_set_trace(node_count, operations) with union by size and path compression; return connected-query booleans. node_count is a nonnegative integer; operation names are 'union' or 'connected', with endpoints in 0 <= endpoint < node_count.
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
def disjoint_set_trace(node_count, operations):
parent = list(range(node_count))
size = [1] * node_count
def find(node):
while parent[node] != node:
parent[node] = parent[parent[node]]
node = parent[node]
return node
results = []
for operation, left, right in operations:
left_root, right_root = find(left), find(right)
if operation == 'connected':
results.append(left_root == right_root)
elif left_root != right_root:
if size[left_root] < size[right_root]:
left_root, right_root = right_root, left_root
parent[right_root] = left_root
size[left_root] += size[right_root]
return resultsUse the actual connectivity Lab on four nodes. Union (1, 2) first finds that endpoint 1 already belongs to root 0, so it joins root 2 to root 0 rather than relinking arbitrary endpoint 1.
print(disjoint_set_trace(4, [('union', 0, 1), ('union', 1, 2), ('connected', 0, 2), ('connected', 0, 3)])) followed by print(disjoint_set_trace(0, []))
| Step | Executed statement | State | Why |
|---|---|---|---|
| 1 | parent = list(range(node_count)); size = [1] * node_count |
parent = [0, 1, 2, 3]; size = [1, 1, 1, 1] |
Every node begins in a one-node component. |
| 2 | parent[right_root] = left_root; size[left_root] += size[right_root] |
union (0, 1): parent = [0, 0, 2, 3]; size[0] = 2 |
Equal sizes keep the left root; only root metadata is authoritative. |
| 3 | left_root, right_root = find(left), find(right) |
union (1, 2): left_root = 0; right_root = 2 |
Endpoint 1 is not a root, so its representative must be found. |
| 4 | parent[right_root] = left_root; size[left_root] += size[right_root] |
parent = [0, 0, 0, 3]; size[0] = 3 |
Joining roots preserves every member of both existing components. |
| 5 | results.append(left_root == right_root) |
queries (0, 2) and (0, 3) produce [True, False] |
Equality of representatives answers connectivity; immediate parent coincidence is not the definition. |
| Output | |
|---|---|
| 1 | [True, False] |
| 2 | [] |
The representative is a component name, not an original graph path. A repeated union of already-connected nodes changes neither partition nor size. The iterative Lab uses path halving; the separate compression Lab recursively flattens a supplied valid parent forest and still has Python depth limits.
Choose DSU for incremental undirected connectivity, cycle checks while adding edges, or Kruskal. Choose DFS/BFS when actual paths, distances, directed reachability, or component contents are needed.
Define root identity, then separate correctness (same root means same component) from optimizations (compression and size). State amortized complexity across the complete operation sequence.
Trace Disjoint-Set Connectivity(opens in a new tab) isolates operations; Number of Islands(opens in a new tab) is usually simpler with traversal unless cells arrive dynamically.
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Disjoint Set Union itself is taught as an interview abstraction.
Verify in Python docs(opens in a new tab)Interview bounds depend on the stated representation, input model, and real Python operations.
| Operation | Average | Worst | Interview note |
|---|---|---|---|
| Initialize n nodes | O(n) | O(n) | Each node begins as its own parent with root size one. |
| One size-weighted union or find | O(alpha(n)) amortized | O(log(n + 1)) | Iterative path-halving connectivity Lab; inverse-Ackermann bound applies over a sequence, not worst-case constant time. |
| Process m connectivity operations | O(n + m * alpha(n)) amortized | O(n + m * alpha(n)) sequence bound | Includes initialization and returned query results; each operation does bounded finds under size weighting/path halving. |
O(n) for initialize n nodes; O(1) for one size-weighted union or find; O(n + m) for process m connectivity operations.
These are the mistakes most likely to survive a happy-path example and fail a boundary case.
Two connected nodes can have different immediate parents before compression.
Prevent it: Compare completed find results, not raw parent entries.
connected = parent[left] == parent[right]connected = roots[left] == roots[right]Where you will hit this: Answer Connected Queries with Union-Find(opens in a new tab)
Changing one interior parent can detach only part of its old component, corrupting the partition.
Prevent it: Find both roots and change the losing root's parent.
parent[right] = leftparent[right_root] = left_rootWhere you will hit this: Answer Connected Queries with Union-Find(opens in a new tab)
The same component cannot be merged with itself. Adding its own size double-counts members.
Prevent it: Skip union when both representative roots match.
parent[right_root] = left_root
size[left_root] += size[right_root]if left_root != right_root:
parent[right_root] = left_root
size[left_root] += size[right_root]Where you will hit this: Number of Islands(opens in a new tab)
Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.
python-docs · checked 2026-07-27