Skip to the page

Graphs and grids · senior

Union-find (light)

Union-find keeps groups of connected items with a parent array, where find walks to the group's root (with path compression) and union joins two roots, making 'are these connected?' almost O(1) as edges arrive.

The notes

What you must know

  • parent[i] = i at the start; find(x): while parent[x] != x, go up; path compression points nodes closer to the root. Write find with a loop, because a recursive find can hit the recursion limit on long chains.
  • union(a, b): join the two ROOTS, attaching the smaller tree under the bigger root (union by size); keep a component count that goes down by one on each successful union.
  • Use it when edges arrive one by one and you need connectivity after each (islands II, accounts merge, redundant connection).
  • For a one-time count of components, BFS or DFS is equally good; say why you picked union-find.
  • Redundant connection: the first edge whose two ends already share a root closes a cycle.
  • With path compression and union by size, each operation is almost O(1) (the inverse Ackermann function, below 5 for any real input).

The red pen

Common traps: mistake → fix

  • Mistake: Union by setting parent[a] = b directly

    Fix: you must join ROOTS, not the nodes.

  • Mistake: Union-find gives the path between nodes

    Fix: it only answers 'same group?'.

  • Mistake: Without any optimisation union-find is still O(1)

    Fix: a chain can make find O(n).

Easy to hard

Questions interviewers ask, easy to hard

  1. Count connected components in an undirected graph.
  2. Find the edge that creates a cycle.
  3. Islands are added one cell at a time; report the count after each addition.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview