hubUnion Find

Union Find: when to spot it, explain it, and practice it

Union find shines when the graph is not traversed once but merged repeatedly. If the problem keeps asking whether two things now belong to the same component, DSU is often the right abstraction.

Pattern coverage

30+

Best first move

Map each item to an index before writing DSU code.

Common failure point

Forgetting path compression and getting near-linear operations.

When this pattern should come to mind

The problem is about connectivity after repeated merge operations.
You need to detect whether adding an edge creates a cycle.
Counting connected components matters more than path details.

Checklist before you code

Map each item to an index before writing DSU code.
Use path compression in find and union by rank or size.
Name clearly what a successful union means for the answer.
Count components carefully if unions can fail.

The solving flow that works well in interviews

1

Initialize each node as its own parent.

2

Compress paths during find so future queries stay cheap.

3

Merge roots instead of raw nodes.

4

Treat a failed union as information, not as an error.

5

If needed, derive the answer from unique roots or successful unions.

Common variants

Connectivity check

Check whether two nodes are connected after a series of unions.

Cycle detection

If union fails because roots match, the new edge creates a cycle.

Component counting

Track how many connected components remain after merges.

Template preview

PythonPublic preview
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]

    def union(self, a, b):
        pa, pb = self.find(a), self.find(b)
        if pa == pb:
            return False
        if self.rank[pa] < self.rank[pb]:
            pa, pb = pb, pa
        self.parent[pb] = pa
        if self.rank[pa] == self.rank[pb]:
            self.rank[pa] += 1
        return True

A more useful problem ladder for practice

This is not a random list. It is ordered to help candidates build recognition first, add key variants next, and then increase pressure with harder cases.

High-frequency mistakes

warning

Forgetting path compression and getting near-linear operations.

warning

Unioning raw nodes instead of their roots.

warning

Not normalizing labels when input items are strings or emails.

warning

Counting components without handling duplicate edges correctly.

Recommended practice path

1

Start with redundant connection and province counting.

2

Then solve email/account merging problems.

3

After that, add equation satisfiability or graph grouping questions.

4

Finally combine DSU with sorting in MST-style questions.

Union Find Pattern Guide | LeetCode Interview Prep - Interview AiBox