Skip to content

What is Union Find?

Data Structures·5 min·Python code

Union Find, known as disjoint set union (DSU), tracks which items share a group while groups keep merging. Find returns the group of an item, and union joins two groups. Path compression and union by size make both cost almost constant time.

Union Find Groups and Representatives

Picture a hall of people forming teams. Every team selects one person to speak for it. Checking whether two people share a team means asking for their speakers and comparing the two names.

That speaker is the representative, known as the root. Every item stores a parent, and following parents leads to the root. Merging two teams takes one pointer, so one root points at the other.

Groups never split in this structure, and that keeps every step small.

Find, Union and Two Tricks for Speed

Plain versions degrade into a long chain, so every find walks a list. Two small changes fix that.

Merging by size hangs the smaller tree under the bigger one, so trees stay shallow. Flattening paths points every node on the way to the root straight at it while you find, so the next lookup takes one step.

Together those tricks bring the amortised cost down to the inverse Ackermann function, which stays under five for any practical input.

Union Find vs Graph Traversal

Breadth-First Search and Depth-First Search answer which nodes connect for a graph you already hold. DSU answers the same question while edges still arrive, and the answer is ready after every edge.

That makes it the engine behind Kruskal's minimum spanning tree, where you add the cheapest edge unless it closes a cycle. Cycle detection in undirected graphs and problems that merge accounts, islands or intervals depend on it too.

Practise on CodeStory's Union Find practice problems.

Union Find Code Example in Python

pythonDisjoint set union in Python with path compression and union by size.

class DSU:
    def __init__(self, n):
        self.parent = list(range(n))   # every item starts in its own group
        self.size = [1] * n

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]   # path compression
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False               # already together: this edge closes a cycle
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra            # hang the smaller tree under the bigger
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        return True

    def connected(self, a, b):
        return self.find(a) == self.find(b)

Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App

Union Find Time and Space Complexity

TimeO(a(n)) amortised per find or union, where a is the inverse Ackermann function
SpaceO(n) for the parent and size arrays

Without them, the worst case slides back to O(n) per find. Those two tricks are the algorithm, not an optimisation.

Watch Union Find Merge Groups

Seeing roots move and trees flatten shows why two small tricks matter. Follow the merges on your own input, one step at a time.

When to Use Union Find

  • You track connected components while edges keep arriving, instead of repeating a traversal.
  • You build Kruskal's minimum spanning tree and take an edge only when it joins two different groups.
  • You detect cycles in an undirected graph, since an edge inside one group closes a cycle.
  • You merge items that match, like duplicate accounts, islands on a grid or equal variables.

Mistakes to Avoid

  • Expecting groups to split. DSU merges, and undoing a union needs extra work.
  • Using it on directed graphs. Edges have no direction here, so choose a traversal or strongly connected components instead.
  • Asking for routes. DSU says whether two items connect, not which path joins them.
  • Using it for one time components on a fixed graph. One BFS or DFS is simpler.

Union Find FAQs

What is the time complexity of Union Find?

With both tricks, every find or union costs O(a(n)) amortised, where a is the inverse Ackermann function. That stays under five steps for any practical n, so people call it constant.

Should I use union by rank or union by size?

Both keep trees shallow, and both work. Size hangs the smaller tree under the larger one, while rank uses an upper bound on height. Size is easier to follow because the root holds the group size.

Why does path compression matter?

Path compression flattens the tree while you answer a query. Every node on the path points straight at the root, so later lookups take one step instead of walking the chain again.

Should I use Union Find or DFS for connected components?

DFS works when the graph is ready before you start. Union Find wins when edges arrive over time, or when you need the answer after every edge, like in Kruskal's algorithm.

What does DSU stand for?

DSU stands for disjoint set union. Disjoint means no item sits in two groups at once, and union means joining two groups into one.

Can Union Find detect a cycle?

Yes, in undirected graphs. When union finds that both ends of an edge share a root, the edge closes a cycle. Code above returns False in that case.

How do I practise Union Find on CodeStory?

Watch merges in the visualiser, write find and union yourself, then try CodeStory's practice problems.

Related Guides

Guides are step one. In a CodeStory batch you code find and union yourself, then explain every root in a scored mock round.

Talk to a Mentor

Stuck on Union Find? Get a Free Callback

Tell CodeStory which Union Find step confuses you, and a mentor shapes your next steps.

  1. 1CodeStory finds your starting point, from your first group to interview ready.
  2. 2CodeStory explains online and campus batches, with timings for your mornings or evenings.
  3. 3You decide. No pressure, no payment on the call.

Get a Free Callback

I am a
I want to learn

CodeStory dials your number only for this callback.