🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Union-Find (Disjoint Set) — Connected Components — Complete Beginner Guide

Data Structures FoundationsUnion-Find (Disjoint Set) — Connected Components🟢 Free Lesson

Union-Find (Disjoint Set) — Connected Components — Complete Beginner Guide

Learning Objectives

  • Model elements as parent pointers
  • Implement find with path compression
  • Implement union by rank or size
  • Explain near constant amortized cost
  • Count connected components in a graph

What Problem Does Union-Find Solve?

Union-find tracks a collection of disjoint sets and supports two operations.

OperationQuestion or Action
findWhich set owns this element
unionMerge two sets into one

Classic uses include connected components, cycle detection, Kruskal minimum spanning tree, and account grouping by network connections.

Basic Parent Array

Each element points to a parent. Roots point to themselves and name their set.

python
class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n
        self.count = n

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

    def union(self, a, b):
        ra = self.find(a)
        rb = self.find(b)
        if ra == rb:
            return False
        # union by rank
        if self.rank[ra] < self.rank[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        if self.rank[ra] == self.rank[rb]:
            self.rank[ra] += 1
        self.count -= 1
        return True

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


uf = UnionFind(6)
uf.union(0, 1)
uf.union(1, 2)
uf.union(3, 4)
print(uf.connected(0, 2))  # True
print(uf.connected(0, 3))  # False
print(uf.count)            # components remaining

Path Compression

After find walks to the root, rewrite every visited node to point straight at the root. The next lookup becomes nearly free.

Without compression, chains degrade toward O(n) per find. With compression, long chains flatten after a few operations.

Union by Rank

Always attach the shorter tree under the taller tree. Rank approximates height without storing full height details.

TechniqueEffect
Naive parent linkTrees can become deep chains
Union by rankKeeps height small
Path compressionFlattens during finds
Both combinedAmortized nearly O(1)

Complexity

The inverse Ackermann function grows incredibly slowly. In practice it stays below five for any realistic n, so operations feel constant time.

VariantTime per Op
NaiveO(n) worst
Rank onlyO(log n)
Compression onlyO(log n) amortized
Rank plus compressionNearly O(1) amortized
SpaceO(n)

Counting Connected Components

Initialize n sets. Union every edge. The final count attribute equals the number of components.

python
def count_components(n, edges):
    uf = UnionFind(n)
    for a, b in edges:
        uf.union(a, b)
    return uf.count


edges = [(0, 1), (1, 2), (3, 4)]
print(count_components(6, edges))  # 3

Cycle Detection

Add edges one by one. If an edge joins two nodes already connected, that edge closes a cycle.

python
def has_cycle(n, edges):
    uf = UnionFind(n)
    for a, b in edges:
        if not uf.union(a, b):
            return True
    return False


print(has_cycle(3, [(0, 1), (1, 2), (0, 2)]))  # True

Kruskal Preview

Kruskal sorts edges by weight and adds an edge only when its endpoints sit in different sets. Union-find answers that question fast and powers the whole algorithm.

Union-Find versus BFS Components

CriteriaUnion-FindBFS or DFS
Incremental edgesExcellentNeeds rebuild
One-shot scanFineNatural
Extra traversal detailNo paths storedCan store paths
ComplexityNearly linear totalO(V plus E)

Union-Find Dry Runs

Trace a six-element union-find without optimizations first to see deep trees form. Then re-run the same unions with union by rank and path compression and compare heights. The optimized forest stays shallow because small trees attach under large ones and finds flatten paths as a side effect.

python
def show_parents(parent):
    return list(parent)


parent = list(range(5))
# naive union makes 1 point to 0
parent[1] = 0
print(show_parents(parent))
# later find path compression rewires intermediate nodes

Use a step table for interviews:

StepActionParent SketchCount
1init 0..4each roots5
2union 0 11 under 04
3union 2 33 under 23
4union 0 2tree under 02
5connected 3 1true after find2

Practice explaining why amortized cost stays nearly constant even though a single unlucky find could still walk a longer path.

Union-Find Versus Graph Search

Both union-find and BFS or DFS can label connected components, but they optimize for different situations.

Union-find thrives when edges arrive incrementally. You never rebuild a full adjacency structure; each new edge is a single union. Kruskal minimum spanning tree and offline connectivity questions lean on that property.

BFS or DFS thrives when the full graph is already stored and you also want paths, distances, or orderings. Component labels fall out as a byproduct of a standard traversal.

SituationPrefer
Edges stream over timeUnion-find
Need actual path examplesBFS or DFS
Many connectivity queries during buildUnion-find
Need neighbor lists for other algorithmsAdjacency list plus traversal
Cycle check while adding edgesUnion-find

Knowing both lets you match the tool to the data flow instead of forcing one pattern onto every problem.

Key Takeaways

💡

  • Union-find maintains disjoint sets with find and union
  • Path compression and union by rank deliver near O(1) operations
  • Component counting needs only unions over all edges
  • Cycle detection flags an edge that joins already connected nodes
  • Kruskal shortest spanning tree logic depends on this structure

Practice Questions

  1. Trace union and find on elements zero through five without path compression and measure tree depth.
  2. Explain how union by rank prevents the worst deep-chain shape.
  3. Detect whether an undirected graph has a cycle using only union-find.

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Data Structures Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement