Skip to main content

Union Find

What union find means, when connecting and querying components quickly matters more than traversing everything each time.

Andrews Ribeiro

Andrews Ribeiro

Founder & Engineer

What it is

Union find is a structure for maintaining groups of connected elements.

It is good at answering two questions:

  • are these two items in the same group?
  • how do I merge these groups now?

When to use it

It appears when connectivity changes as the process goes on:

  • connecting nodes
  • detecting components
  • checking whether a new edge creates a cycle

Common mistake

The classic mistake is doing a full traversal every time a new connection appears.

If the problem has many unions and many connectivity checks, that scales badly.

Better question

Before using it, ask:

  1. does the problem talk about groups gradually merging?
  2. will I query connectivity many times?
  3. is the graph changing over time?

Keep exploring