teacher
Sign in

Disjoint Set Union

Track which items belong to the same group while groups merge, using union by size and path compression for near-constant time per operation.

40 minCF 1300–19004 interactive10 problems

The problem

You have nn items and each starts alone in its own group. Two kinds of events happen:

  • union(a, b): merge the group of aa with the group of bb.
  • find / same(a, b): are aa and bb in the same group? Sometimes also: how big is the group, how many groups are left?

A friendship network where new friendships keep appearing is the standard picture. Groups only merge, they never split.

1 of 8