Union-find
A union-find structure keeps each group as a tree of parent pointers, so two items are in the same group when they reach the same root, and joining by size with path compression makes each operation nearly constant time.
A union-find structure keeps each group as a tree of parent pointers, so two items are in the same group when they reach the same root, and joining by size with path compression makes each operation nearly constant time.