Union-Find (Disjoint Set) — Data Structures

Union-find (a disjoint set) stores groups that don't overlap as a parent array: each person points to their parent, one person in their group. Every group is…

On the first day of university, nobody knows anybody. Andi meets Budi, and Citra meets Dina. At lunch Budi meets Citra. Now Andi and Dina are in the same circle of friends, though they've never talked. In the code they become people 0 to 3 (Andi 0, Budi 1, Citra 2, Dina 3), plus person 4, who hasn't met anyone yet.

Union-find (also called a disjoint set) stores groups like this circle of friends: several groups that don't overlap, so each person is in only one group. It does two things quickly: it answers "are these two people in the same group?", and it merges their groups. At first everyone is on their own. Every time two people meet, their groups join into one.

Every group has a leader

Each person points to one person in their group, called their parent. Keep following parents upward and you reach the group's leader (the root): the person whose parent is themselves. So every group is a tree, with the leader at the top. Two people are in the same group when they have the same leader.

This code makes a union-find for n people:

class UnionFind {
  constructor(n) {
    this.parent = Array.from({ length: n }, (_, i) => i); // [0, 1, 2, ...]
  }

  find(x) {
    while (this.parent[x] !== x) x = this.parent[x]; // climb up to the leader
    return x;
  }

  union(a, b) {
    const ra = this.find(a);
    const rb = this.find(b);
    if (ra === rb) return false; // already in one group
    this.parent[rb] = ra;        // b's leader now follows a's leader
    return true;
  }

  connected(a, b) {
    return this.find(a) === this.find(b);
  }
}

Here's how it goes with 5 people:

Step parent Groups
start [0, 1, 2, 3, 4] 5 groups: {0} {1} {2} {3} {4}
union(0, 1) [0, 0, 2, 3, 4] 4 groups: 1 goes under 0
union(2, 3) [0, 0, 2, 2, 4] 3 groups: {0, 1} {2, 3} {4}
union(1, 2) [0, 0, 0, 2, 4] 2 groups: 1's leader is 0, 2's leader is 2, so 2 goes under 0

After union(1, 2), find(3) climbs from 3 to 2 and then to 0, so 3's leader is now 0, the same as 1's. In the story, Andi (0) and Dina (3) are now in one group.

Counting the groups

Every group has exactly one leader. So the number of groups is the number of people whose parent is themselves. In [0, 0, 0, 2, 4] the leaders are 0 and 4: that's 2 groups. In code: loop over every index and count the ones where this.parent[i] === i.

Keeping it fast

In the worst case, unions can build a long chain (0 under 1, 1 under 2, and so on), and find has to climb one step at a time. That's O(n). Two improvements prevent it:

With both together, find and union become almost O(1). This means that, averaged over many operations in a row, each one takes nearly the same time however much data there is. In the exercise, neither is required. The simple version above is enough.

Where it's used

Union-find fits when the question is "which group is this person in?" and groups only ever merge, never split. Examples are counting friend groups, checking whether two computers on a network are connected, and Kruskal's algorithm. Kruskal finds a minimum spanning tree: the set of roads that links every city for the lowest total cost. Before adding a road, it asks union-find whether the two cities at its ends are already connected. If they are, it doesn't use that road, so no loop (a path that comes back to the city it started from) forms.

💡 Path compression and union by rank in code

This is a find and a union that use both improvements:

// in the constructor: this.rank = new Array(n).fill(0);

find(x) {
  if (this.parent[x] !== x) {
    this.parent[x] = this.find(this.parent[x]); // hang it straight on the leader
  }
  return this.parent[x];
}

union(a, b) {
  let ra = this.find(a);
  let rb = this.find(b);
  if (ra === rb) return false;
  if (this.rank[ra] < this.rank[rb]) [ra, rb] = [rb, ra]; // the shorter one goes under
  this.parent[rb] = ra;
  if (this.rank[ra] === this.rank[rb]) this.rank[ra]++;
  return true;
}

rank is a rough height of each leader's tree. [ra, rb] = [rb, ra] swaps the values of ra and rb, so the leader of the shorter tree is always the one placed under. If both rank values are the same, the merged tree grows 1 level taller, so the new leader's rank goes up by 1 too. This find is recursive: on the way back from the leader, everyone on the path is pointed straight at the leader.

⚠️ A parent taken for the leader, and members left behind

TL;DR: Union-find (a disjoint set) stores groups that don't overlap as a parent array: each person points to their parent, one person in their group. Every group is a tree, and the leader (root) at its top is the person whose parent is themselves. find(x) climbs to the leader, union(a, b) places one leader under the other, and two people are in the same group when their leaders match. The number of groups is the number of leaders. Path compression (placing everyone find passes directly under the leader) plus union by rank (the shorter tree goes under the taller one) make the operations almost O(1). Kruskal's algorithm, which finds the cheapest network of roads, uses union-find to skip any road between two cities that are already connected.

⚡ Every group has a leader

Write:

find(x) {
  while (this.parent[x] !== x) x = this.parent[x]; // climb up to the leader
  return x;
}

Meaning: Union-find stores groups that don't overlap, and each person has a number: 0, 1, 2 and so on. this.parent is an array that holds each person's parent, the one person in their group they point to. A leader (root) is someone whose parent is themselves. find(x) climbs from parent to parent until it reaches the leader. Two people are in the same group when their find returns the same leader.

⚡ Merge: a leader under a leader

Write:

const ra = this.find(a);
const rb = this.find(b);
if (ra === rb) return false; // already in one group
this.parent[rb] = ra;        // b's leader now follows a's leader
Guess first: this.parent holds [0, 0, 0, 2, 4], so 3's parent is 2. Who is 3's leader?

Person 0. From 3 it climbs to 2, then to 0, whose parent is itself. So always compare what find returns, not the parents.

Meaning: ra and rb are the leaders of a and b. If they differ, b's leader is placed under a's leader. Moving just the leader is enough: everyone else follows, because their way up goes through that leader. The number of groups is the number of leaders, the people i where this.parent[i] === i.

⚡ Almost O(1)

Meaning: Without improvements, a group can become a long chain, and find has to climb one step at a time: O(n). Path compression places everyone find passes directly under the leader. Union by rank puts the shorter tree under the taller one. Together they make the operations almost O(1). Kruskal's algorithm, which finds the cheapest network of roads, uses union-find to skip any road between two cities that are already connected.

What you will learn