Skip to contentKEEP THE CRAFTTHE SANCTUARY

Union-Find

Represent disjoint components by parent roots and merge only distinct representatives. Path compression changes routes to a root, not membership; balancing reduces future traversal while redundant edges leave component count unchanged.

2 practice exercises2 interview problems

Recognize it when Undirected edges arrive incrementally and connectivity queries repeat.

Checking your account…

Union-Find Code Labs

Represent Components by Roots

Union-find stores a parent forest where each component has one root that parents itself. Two nodes are connected exactly when find returns the same root.

Compress Paths During Find

Path compression rewires visited nodes toward the root, preserving component identity while accelerating later queries. Apply it consistently in recursive or iterative find.

Trace Union-Find State

Reference
def union_find_trace(n,edges):
    parent=list(range(n));size=[1]*n;trace=[]
    def find(node):
        while node!=parent[node]:parent[node]=parent[parent[node]];node=parent[node]
        return node
    for left,right in edges:
        a,b=find(left),find(right);merged=a!=b
        if merged:
            if size[a]<size[b]:a,b=b,a
            parent[b]=a;size[a]+=size[b]
        trace.append([parent.copy(),size.copy(),merged])
    return trace
Practice

Implement union_find_trace(n,edges). Return [parent,size,merged] after each union using path compression and union by size.

Public tests

  • Attach smaller roots once

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

Trace Union-Find State

def union_find_trace(n,edges):
    parent=list(range(n));size=[1]*n;trace=[]
    def find(node):
        while node!=parent[node]:parent[node]=parent[parent[node]];node=parent[node]
        return node
    for left,right in edges:
        a,b=find(left),find(right);merged=a!=b
        if merged:
            if size[a]<size[b]:a,b=b,a
            parent[b]=a;size[a]+=size[b]
        trace.append([parent.copy(),size.copy(),merged])
    return trace

A Redundant Edge Changes No Component

The existing state Lab uses size balancing and path halving. Predict why the second edge attaches 0 under 1, even though 0 is the smaller numeric label; labels do not determine balance.

Step Executed statement State Why
First roots a,b=find(left),find(right);merged=a!=b a=1, b=2, merged=True Distinct singleton components can merge.
Attach 2 parent[b]=a;size[a]+=size[b] parent=[0,1,1,3], size[1]=2 Only the root size now represents the combined component.
Balance second edge a,b=find(left),find(right);merged=a!=b;a,b=b,a; parent[b]=a;size[a]+=size[b] after edge (0,1): parent=[1,1,1,3], size[1]=3 Root 0 is smaller than root 1, so it becomes the child. The swap is executed in the actual smaller-size conditional branch.
Third edge a,b=find(left),find(right);merged=a!=b both representatives=1, merged=False Nodes 2 and 0 are already connected; no attachment or size update occurs.
Snapshot trace.append([parent.copy(),size.copy(),merged]) last snapshot retains the same arrays Nonroot size entries are old values, not independent component sizes.
Print Output
print(union_find_trace(4, [[1, 2], [0, 1], [2, 0]])) [[[0, 1, 1, 3], [1, 2, 1, 1], True], [[1, 1, 1, 3], [1, 3, 1, 1], True], [[1, 1, 1, 3], [1, 3, 1, 1], False]]

For first_redundant_edge, the same root comparison is the answer condition. A representative can change after later unions; it is an internal component handle, not a permanent application ID.

Union Smaller Trees Under Larger

Union by size attaches the root with fewer nodes under the larger component; it does not compare actual depth. Union by rank instead compares a height-bound rank. Update metadata only on roots and only when two distinct components actually merge.

Find the First Redundant Edge

Reference
def first_redundant_edge(n,edges):
    parent=list(range(n));size=[1]*n
    def find(node):
        if parent[node]!=node:parent[node]=find(parent[node])
        return parent[node]
    for left,right in edges:
        a,b=find(left),find(right)
        if a==b:return [left,right]
        if size[a]<size[b]:a,b=b,a
        parent[b]=a;size[a]+=size[b]
    return []
Practice

Implement first_redundant_edge(n,edges). Return the first edge whose endpoints are already connected, or [].

Public tests

  • Reject an edge inside one component

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

Find the First Redundant Edge

def first_redundant_edge(n,edges):
    parent=list(range(n));size=[1]*n
    def find(node):
        if parent[node]!=node:parent[node]=find(parent[node])
        return parent[node]
    for left,right in edges:
        a,b=find(left),find(right)
        if a==b:return [left,right]
        if size[a]<size[b]:a,b=b,a
        parent[b]=a;size[a]+=size[b]
    return []

Use Union Find for Incremental Connectivity

Union-find excels at edge additions and repeated connectivity queries, with near-constant amortized operations. It does not directly support deletions, shortest paths, or component traversal; graph search is better for those.

Explain It in an Interview

Say: “Parent roots identify components. Find compresses paths, union attaches the smaller root, and an edge between equal roots is redundant.” State O((n + m) alpha(n)) time and O(n) space.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Union-Find

Find the root and flatten the path; hang the small tree under the big.

You repeatedly connect items and ask whether two items are already connected.

Trigger words

  • redundant connection
  • number of provinces
  • accounts merge
  • edges one by one
  • already connected?
  • minimum spanning tree
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.size = [1] * n

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

    def union(self, a, b):
        root_a = self.find(a)
        root_b = self.find(b)
        if root_a == root_b:
            return False                  # already connected
        if self.size[root_a] < self.size[root_b]:
            root_a, root_b = root_b, root_a
        self.parent[root_b] = root_a
        self.size[root_a] += self.size[root_b]
        return True

Spot it when

  • 'Redundant connection', 'number of provinces', 'accounts merge'.
  • Edges arrive one by one.

Remember

  • union returns False when the two items were already connected: that edge closes a cycle.
  • Path shortcuts plus union by size make each operation almost O(1).

How problems bend it

  • Redundant connection: Return the first edge whose union returns False.
  • Count components: Start with n components and subtract one for every successful union.
  • Minimum spanning tree (Kruskal): Sort edges by weight; keep an edge only when union returns True, and add its weight.

Python Version Note

Complexity & Invariants

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

OperationAverageWorstInterview note
m find/union operations plus initializationO(n + m alpha(n)) amortizedO(n + m alpha(n)) aggregateCompression and union by size/rank are both required for the bound.
Parent/size snapshot traceO(n + m alpha(n) + mn)O(n + m alpha(n) + mn) aggregateEach of m operations copies two length-n arrays; trace output itself retains O(mn) cells.

Space

O(n) parent and size storage; full parent/size trace snapshots add O(mn).

Assumptions

  • Amortized aggregate complexity does not mean every individual find takes constant time.
  • A nonroot size slot can remain stale; read sizes only through current roots.

Invariants Worth Saying Aloud

  1. Each parent chain terminates at one self-parented root.
  2. Only roots own authoritative size metadata.
  3. Joining distinct roots reduces the component count by one; redundant edges do not.

When To Use Or Avoid Union-Find

Use It When

  • Use union-find for monotone edge additions, component counts or Kruskal cycle rejection.
  • Combine path compression with union by size or rank for amortized near-constant operations.

Choose Another Tool When

  • Deletions or actual path reconstruction need a different structure or graph traversal.
  • Directed reachability is not an equivalence relation and cannot be represented by ordinary union-find.

Common Pitfalls

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

Comparing immediate parents rather than roots

In parent [0,0,1], node 2 reaches root 0 through node 1. Its immediate parent differs from node 0’s, but the nodes are connected.

Prevent it: Follow parent links to representatives before comparing.

Avoid

connected = parent[0] == parent[2]

Use instead

node = 2
while node != parent[node]: node = parent[node]
connected = parent[0] == node

Decrementing count for a redundant edge

When roots are equal, no component merger occurs. Subtracting one falsely reduces the count.

Prevent it: Change count only if representatives differ.

Avoid

count -= 1

Use instead

count -= int(a != b)

Updating a child size instead of the root size

After root 1 is attached under root 0, size[0] must become 2. Updating size[1] leaves balancing metadata at the representative wrong.

Prevent it: Accumulate size on the surviving root.

Avoid

size[b] += size[a]

Use instead

size[a] += size[b]

Reviewed References

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