Skip to content

Disjoint Sets Basics

Lesson 1 of 4 · 5 min

Disjoint Sets Basics

Step 1 of 8

Six elements, each its own parent. That is six separate groups, before anything is joined.

The Idea

Keep one array: parent[x] is who x points at. Follow the pointers and you stop at an element that points at itself — the root, which is the group's name.

find walks up to that root. union finds both roots and hangs one under the other, merging two groups with a single write.

Real-World Example

A photo library clustering faces. When you confirm two clusters are the same person it does not relabel every photo — it points one cluster at the other. Asking "same person?" later just compares the two labels you arrive at.

The Code

Your turn

Fill in the blank.

parent = [0, 0, 2, 2]
def find(x):
  while parent[x] ___ x:
      x = parent[x]
  return x
print(find(1), find(3))   # 0 2

Mini quiz

1 / 3

How is the root of a group recognised?