Skip to the page

Graphs and grids · senior

Union-find (light) in JavaScript

Union-find keeps groups of connected items in a parent array: find walks to the group's root (with path compression) and union joins two roots, so 'are these connected?' is almost O(1) as edges arrive. In JavaScript, typed arrays keep the parent and size arrays compact.

The notes

What you must know

  • parent[i] = i at the start; find(x): while parent[x] !== x, jump up; path compression points nodes closer to the root.
  • union(a, b): attach the smaller tree under the bigger root (union by size); keep a component count.
  • 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/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.
  • Set up: parent = Int32Array.from({ length: n }, (_, i) => i) and size = new Int32Array(n).fill(1). For string items (emails in accounts merge), first map each string to an index with a Map.

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?'.

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