Skip to content
DSA in JavaScript
← All patterns

Union-Find

0/12 solved

What it is

Track which items belong to the same group, and merge two groups in nearly constant time.

Used for

Connected components, "are these two connected?", detecting cycles, Kruskal's algorithm.
item
0
1
2
3
4
parent
0
1
2
3
4

Step 1 of 6

Goal: keep track of which items belong to the same group, and merge groups quickly. Start with 5 separate groups. Each item points to a parent; an item that points to itself is the leader of its group.

You see

  • Dynamic connectivity
  • Merging groups
  • Detect a cycle in an undirected graph
  • Minimum spanning tree

Learn it in

Kruskal's AlgorithmDisjoint SetKruskal's Algorithm

Template

const parent = [];const find = x => (parent[x] === undefined || parent[x] === x ? (parent[x] = x) : (parent[x] = find(parent[x])));const union = (a, b) => { parent[find(a)] = find(b); };

Practice problems