Pattern

Union-find

Track which elements belong to the same group under repeated merges, answering "same group?" in near-constant time.

What it is

Union-find (disjoint set union) maintains a partition of elements into groups and supports two operations cheaply, even after many merges: find (which group is this element in?) and union (merge two groups). With path compression and union by size or rank, both run in near-constant amortized time. It's the right structure whenever the question is fundamentally about connectivity that builds up incrementally — you process a stream of relationships and need to know, at any point, whether two things are already linked — rather than about paths, distances, or ordering.

When it applies

Tells in the problem

The classic mistake

The mistake interviewers commonly report is implementing find without path compression (or union without joining by size/rank), which still produces correct answers on small examples but degrades toward O(n) per operation as chains of parent pointers grow long — turning an intended near-linear solution into a quadratic one that times out only at scale. It happens because a naive union-find (plain parent array, no compression) passes every hand-traced example just as well as the optimized version, so the missing optimization is invisible until the input size in the constraints is taken seriously. State explicitly, before coding, that find will compress paths on the way up and that union will attach the smaller tree under the larger one's root — treat these as required parts of the structure, not optional polish.

Questions to start with

All 6 union-find questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.