← Back to Algorithms, page 4

algorithms-0070 · Medium mid

Union-find (disjoint set union): implement find and union with path compression and union by size, and use it to find the edge that creates a cycle.

Each set is a tree with a root representative. find walks to the root and shortens the path on the way; union attaches the smaller tree under the larger root. With both optimisations each operation is O(alpha(n)) amortised, effectively constant. When union finds both endpoints already share a root, that edge closes a cycle.

Full answer

Problem

Implement a disjoint-set structure over 0..n-1 with find(x), union(a, b) and connected(a, b). Then solve "redundant connection": a tree of n nodes (labelled 1..n) had one extra edge added; return the edge that, when removed, leaves a tree (the last such edge in input order).

Example: edges [[1, 2], [1, 3], [2, 3]] return [2, 3]; [[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]] return [1, 4].

Constraints: up to 10^5 nodes and union or find operations.

Brute force

For each new edge, run BFS or DFS to see whether its endpoints are already connected: O(V + E) per edge and O(E * (V + E)) overall. Without the two optimisations, a plain union-find can degrade to O(n) per find on a chain-shaped tree.

Optimal approach

  • parent[i] = i, size[i] = 1 at start.
  • find(x): while x is not its own parent, set parent[x] = parent[parent[x]] (path halving) and move up.
  • union(a, b): find both roots; if equal, return False. Otherwise attach the smaller root under the larger and add sizes.
  • Redundant connection: union each edge in order; the first union that returns False is the answer.

Why it works

Two nodes are connected exactly when they have the same root, because unions only ever merge whole trees. Union by size keeps tree height at O(log n), since a node's depth increases only when its tree at least doubles in size. Path compression flattens the trees further, and the combination gives the inverse Ackermann bound. In the redundant edge problem, an edge whose endpoints are already connected is the one that completes a cycle.

Complexity

O(alpha(n)) amortised per operation (alpha is below 5 for any realistic n), O(n) space. Union by size alone gives O(log n) per operation.

Code

python
import random


class DSU:
    """Disjoint set union with path halving and union by size.
    Each operation is O(alpha(n)) amortised, effectively constant."""

    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.sets = n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]   # path halving
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False                 # already connected: this edge closes a cycle
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra             # attach the smaller tree under the larger
        self.size[ra] += self.size[rb]
        self.sets -= 1
        return True

    def connected(self, a, b):
        return self.find(a) == self.find(b)


def redundant_connection(edges):
    """First edge that joins two already-connected nodes (nodes are 1..n)."""
    dsu = DSU(len(edges) + 1)
    for u, v in edges:
        if not dsu.union(u, v):
            return [u, v]
    return []


def brute_connected(n, edges, a, b):
    adj = {i: set() for i in range(n)}
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    seen, stack = {a}, [a]
    while stack:
        for v in adj[stack.pop()]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return b in seen


if __name__ == "__main__":
    d = DSU(5)
    assert d.union(0, 1) and d.union(3, 4) and not d.union(1, 0)
    assert d.connected(0, 1) and not d.connected(1, 3) and d.sets == 3
    assert redundant_connection([[1, 2], [1, 3], [2, 3]]) == [2, 3]
    assert redundant_connection([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]) == [1, 4]
    rng = random.Random(70)
    for _ in range(300):
        n = rng.randint(1, 15)
        dsu, es = DSU(n), []
        for _ in range(rng.randint(0, 20)):
            u, v = rng.randrange(n), rng.randrange(n)
            dsu.union(u, v)
            es.append((u, v))
            a, b = rng.randrange(n), rng.randrange(n)
            assert dsu.connected(a, b) == brute_connected(n, es, a, b)
    print("all tests passed")

Save as b70_union_find.py and run python3 b70_union_find.py. It prints all tests passed (Python 3.13.5).

Edge cases

union(x, x) (already connected). Nodes labelled from 1 (allocate n + 1). Counting sets: start at n and decrement on each successful union. Union-find does not support splitting sets; deletions need a different structure or offline processing.

Pattern

Incremental connectivity. Union-find powers Kruskal's MST, number of islands with additions, accounts merge (group emails), equations with equality and inequality constraints, and percolation simulations. Weighted union-find extends it to "a / b = k" style relations.

python
import random


class DSU:
    """Disjoint set union with path halving and union by size.
    Each operation is O(alpha(n)) amortised, effectively constant."""

    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n
        self.sets = n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]   # path halving
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False                 # already connected: this edge closes a cycle
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra             # attach the smaller tree under the larger
        self.size[ra] += self.size[rb]
        self.sets -= 1
        return True

    def connected(self, a, b):
        return self.find(a) == self.find(b)


def redundant_connection(edges):
    """First edge that joins two already-connected nodes (nodes are 1..n)."""
    dsu = DSU(len(edges) + 1)
    for u, v in edges:
        if not dsu.union(u, v):
            return [u, v]
    return []


def brute_connected(n, edges, a, b):
    adj = {i: set() for i in range(n)}
    for u, v in edges:
        adj[u].add(v)
        adj[v].add(u)
    seen, stack = {a}, [a]
    while stack:
        for v in adj[stack.pop()]:
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return b in seen


if __name__ == "__main__":
    d = DSU(5)
    assert d.union(0, 1) and d.union(3, 4) and not d.union(1, 0)
    assert d.connected(0, 1) and not d.connected(1, 3) and d.sets == 3
    assert redundant_connection([[1, 2], [1, 3], [2, 3]]) == [2, 3]
    assert redundant_connection([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]) == [1, 4]
    rng = random.Random(70)
    for _ in range(300):
        n = rng.randint(1, 15)
        dsu, es = DSU(n), []
        for _ in range(rng.randint(0, 20)):
            u, v = rng.randrange(n), rng.randrange(n)
            dsu.union(u, v)
            es.append((u, v))
            a, b = rng.randrange(n), rng.randrange(n)
            assert dsu.connected(a, b) == brute_connected(n, es, a, b)
    print("all tests passed")

DSU with path halving and union by size, the redundant-connection solver, and random checks of connected() against BFS reachability.

Complexity

Time: O(alpha(n)) amortised per operation. Space: O(n). Union by size alone gives O(log n); path compression alone gives O(log n) amortised; together they give alpha(n).

By level

Fresher: Implements find and union and explains that same root means same group. Uses it to detect the extra edge in a small example.

Mid: Adds path compression and union by size and explains the height argument. Applies union-find to islands with additions and to Kruskal.

Senior: Discusses rollback DSU for offline queries, weighted union-find for relative values, and concurrency issues when sharing a DSU across threads. Compares union-find with graph traversal for dynamic connectivity workloads.

Key points

  • Same root means same set
  • Union by size bounds height
  • Path compression flattens trees
  • Combined cost is inverse Ackermann
  • Failed union means a cycle edge

Common mistakes

  • Comparing parents instead of roots
  • Attaching the larger tree under the smaller
  • Forgetting to update size on the new root only
  • Expecting union-find to support deletions

Follow-ups

  • How would you support "undo" of the last union (rollback DSU)?
  • How do you handle relations like a / b = 2 with weighted union-find?
  • How would you process edge deletions offline?

Tips

  • Explain why both optimisations matter
  • State alpha(n) as effectively constant
  • Show the redundant-edge use

Evaluation rubric

  • Correct find and union
  • Both optimisations
  • Correct application
  • Correct complexity