Skip to contentKEEP THE CRAFTTHE SANCTUARY

Disjoint Set Union

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 Code Labs

Mental Model

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.

Represent Components by Roots

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.

Compress Find Paths

find follows parents to a root, then rewrites visited parents toward that root. Compression changes shape but never component membership.

Compress Parent Paths

Reference
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, compressed
Practice

Implement 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.

Public tests

  • Verify roots and compressed parents

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compress Parent Paths

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, compressed

Union by Size

Attach 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.

Trace Union Connectivity

Reference
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 results
Practice

Implement 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.

Public tests

  • Verify component connectivity

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Union Connectivity

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 results

Trace Root-Based Union Through a Non-Root Endpoint

Use 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.
Print 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 or Graph Traversal

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.

Representative and Union Mistakes

  • Attaching arbitrary nodes instead of roots corrupts the partition.
  • Updating size on a non-root makes union decisions stale.
  • DSU cannot remove edges or explain the connecting path without additional machinery.
  • Calling the bound worst-case O(1) overstates the amortized guarantee.

Explain It in an Interview

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 Version Note

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)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Initialize n nodesO(n)O(n)Each node begins as its own parent with root size one.
One size-weighted union or findO(alpha(n)) amortizedO(log(n + 1))Iterative path-halving connectivity Lab; inverse-Ackermann bound applies over a sequence, not worst-case constant time.
Process m connectivity operationsO(n + m * alpha(n)) amortizedO(n + m * alpha(n)) sequence boundIncludes initialization and returned query results; each operation does bounded finds under size weighting/path halving.

Space

O(n) for initialize n nodes; O(1) for one size-weighted union or find; O(n + m) for process m connectivity operations.

Assumptions

  • Each node begins as its own parent with root size one.
  • Iterative path-halving connectivity Lab; inverse-Ackermann bound applies over a sequence, not worst-case constant time.
  • Includes initialization and returned query results; each operation does bounded finds under size weighting/path halving.

Invariants Worth Saying Aloud

  1. Every parent chain ends at a self-parent root representing one component.
  2. Union connects distinct roots and updates size only at the surviving root.
  3. Compression changes parent shape but never which nodes share a representative.

When To Use Or Avoid Disjoint Set Union

Use It When

  • Use DSU for incremental undirected components or cycle checks during edge additions.
  • Maintain root-owned size when attaching the smaller component.

Choose Another Tool When

  • Use BFS/DFS for actual paths, directed reachability or component enumeration.
  • Ordinary DSU does not support edge deletion or component splitting.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Comparing immediate parents rather than representatives

Two connected nodes can have different immediate parents before compression.

Prevent it: Compare completed find results, not raw parent entries.

Avoid

connected = parent[left] == parent[right]

Use instead

connected = roots[left] == roots[right]

Attaching an interior node instead of its component root

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.

Avoid

parent[right] = left

Use instead

parent[right_root] = left_root

Increasing size on a union inside one component

The same component cannot be merged with itself. Adding its own size double-counts members.

Prevent it: Skip union when both representative roots match.

Avoid

parent[right_root] = left_root
size[left_root] += size[right_root]

Use instead

if left_root != right_root:
    parent[right_root] = left_root
    size[left_root] += size[right_root]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.