Introduction
Welcome to the final lesson in our graph algorithms module. In the previous lesson, we explored topological sort, an algorithm for ordering nodes in a Directed Acyclic Graph based on their dependencies. We saw how it's used in real-world scenarios like task scheduling and dependency resolution.
Today, we're shifting our focus to a different class of graph problems centered around connectivity. We will learn to use the Union-Find data structure, also known as the Disjoint Set Union (DSU). Its purpose is remarkably specific yet powerful: to efficiently track a collection of disjoint sets and merge them.
This capability makes Union-Find the go-to tool for problems involving connected components, especially in dynamic contexts where you're adding connections and need to query connectivity in near-constant time. By the end of this lesson, you will be able to implement the Union-Find data structure with its crucial optimizations—path compression and union by rank/size—and apply it to solve connectivity problems. This is a common pattern in interviews and has direct applications in network design and large-scale data analysis.
The Core Idea of Union-Find
Imagine you have a set of N items, and each item starts in its own individual group. The Union-Find data structure supports two primary operations:
Find(item): Determines which group an item belongs to by returning a unique representative (or "root") for that group.Union(item1, item2): Merges the groups containingitem1anditem2.
The central question Union-Find answers is: "Are these two items in the same group?" You can answer this by checking if Find(item1) == Find(item2).
Let's start with a video that introduces the data structure and its primary use case: dynamically tracking connected components in a graph.
G-46. Disjoint Set | Union by Rank | Union by Size | Path Compression
This video from 'take U forward' clearly explains the motivation for using a Disjoint Set data structure and introduces its fundamental operations.
Watch the first part of the video, from 00:06 to 04:52. Focus on understanding why a simple DFS/BFS can be inefficient for dynamic connectivity queries and how Union-Find aims to solve this in nearly constant time.
As the video explains, initially, we have N nodes, each forming its own component. As we are given edges, we perform Union operations to merge the components. At any point, we can use Find to check if two nodes belong to the same component.
Internally, these sets are represented as a forest of trees, where each tree corresponds to one set. The root of the tree is the representative of that set.

Key Optimizations: Union by Rank and Path Compression
A naive implementation of Union-Find can result in tall, skinny trees, making the Find operation slow (up to in the worst case). To achieve the promised near-constant time performance, two optimizations are essential.
-
Union by Rank (or Union by Size): This heuristic ensures that our trees stay as flat as possible during
Unionoperations. Instead of arbitrarily connecting one tree to another, we always attach the root of the smaller tree to the root of the larger tree.- Union by Rank: "Rank" approximates the height of the tree.
- Union by Size: "Size" tracks the number of nodes in the tree. Union by size is often more intuitive and equally effective.
-
Path Compression: This optimization is applied during the
Findoperation. As we traverse up from a node to find its root, we "compress" the path by making every node we visit point directly to the root. This drastically speeds up futureFindoperations for any node along that path.
Let's return to the video for a detailed, step-by-step walkthrough of these two critical optimizations.
G-46. Disjoint Set | Union by Rank | Union by Size | Path Compression
This segment provides a detailed dry run of implementing Union-Find, focusing on the mechanics of 'Union by Rank' and 'Path Compression'.
Watch the segment from 04:52 to 19:28. Pay close attention to how the 'parent' and 'rank' arrays are updated during the union operations and how path compression modifies the tree structure when Find is called.

With both optimizations, the amortized time complexity of a single Union or Find operation becomes nearly constant, technically , where is the extremely slow-growing Inverse Ackermann function. For all practical purposes, including interviews, you can state this is amortized constant time.
Idiomatic Go Implementation
While the concepts are universal, seeing a clean implementation in your preferred language is key. The UnionFind data structure in Go can be elegantly represented with a struct containing two slices: one for parent pointers and another for size (or rank).
The following resource provides an excellent, idiomatic Go implementation and demonstrates its use in a common grid-based problem.
Algorithms That Work Well with Go's Mechanics
This article from Alexander Obregon's blog provides a concise and practical Go implementation for Union-Find, which is a great reference for your interviews.
Please read the section 'Union Find with Slice Backing for Grid Grouping' and study the UnionFind struct and its associated methods: NewUnionFind, Find, and Union. Note the iterative implementation of path compression within the Find method and the use of union by size.
Here's the core structure from the article, which you should aim to be able to reproduce:
type UnionFind struct {
parent []int
size []int
}
func NewUnionFind(n int) *UnionFind {
p := make([]int, n)
s := make([]int, n)
for i := 0; i < n; i++ {
p[i] = i
s[i] = 1
}
return &UnionFind{parent: p, size: s}
}
func (uf *UnionFind) Find(x int) int {
// Iterative path compression
for x != uf.parent[x] {
uf.parent[x] = uf.parent[uf.parent[x]] // Point to grandparent
x = uf.parent[x]
}
return x
}
func (uf *UnionFind) Union(a, b int) bool {
ra := uf.Find(a)
rb := uf.Find(b)
if ra == rb {
return false // Already in the same set
}
// Union by size
if uf.size[ra] < uf.size[rb] {
ra, rb = rb, ra // Ensure ra is the larger root
}
uf.parent[rb] = ra
uf.size[ra] += uf.size[rb]
return true
}
Application: Counting Connected Components
The most direct application of Union-Find is to count the number of connected components in a graph. The logic is straightforward:
- Start with
ncomponents, one for each node. - Initialize a
UnionFinddata structure withnelements. - For each edge
(u, v)in the graph, attempt toUnion(u, v). - If the
Unionoperation merges two previously distinct components, decrement the component count by one. - The final count is the answer.
This approach is highly efficient because you process each edge once with near-constant time operations. Let's watch a video that applies this exact logic to solve a LeetCode problem.
Number of Connected Components in an Undirected Graph - Union Find - Leetcode 323 - Python
This NeetCode video solves 'Number of Connected Components' and provides a great walkthrough of how to map the problem directly to the Union-Find data structure.
Watch the full video. The initial discussion compares DFS to Union-Find, which is a good trade-off to understand. Then, focus on how the component count is initialized to 'n' and decremented each time a successful union occurs.
A Staff-Level View: Union-Find in Production Systems
For a Staff-level role, it's not enough to know the algorithm; you should be able to discuss its application and trade-offs in real-world systems. Union-Find is used at scale to solve complex connectivity and mapping problems.
The analytics company Heap wrote a fascinating blog post about using Union-Find to manage user identities across different devices and sessions. This is a perfect example of applying a "textbook" data structure to solve a messy, large-scale engineering challenge.
Applying Textbook Data Structures for Real Life Wins
This article from Heap.io details how they use Union-Find in their production systems. It provides valuable insights into practical implementation challenges and architectural decisions.
Read the sections 'Identity in Heap', 'Union-Find 101', 'Union by Rank and Path Compression', and 'The Solution: From SQL to Application Logic'. Pay attention to how they mapped their business problem to Union-Find and the architectural shift they made (from a slow SQL query to a dedicated Go service) for performance.
Key talking points from this article for an interview:
- Problem Mapping: A complex problem like de-duplicating user identities across multiple anonymous and identified sessions can be modeled as a dynamic connected components problem.
- Performance is Critical: The theoretical efficiency of Union-Find directly translates to real-world performance wins, as seen in their 15x speedup.
- Adapting for Constraints: They couldn't easily implement traditional
union by rankin their distributed system. They devised a clever, stateless "union by hash" heuristic to approximate the same behavior, demonstrating deep engineering trade-offs. - Architecture: Recognizing that the algorithm's performance was hampered by its database implementation (SQL), they moved the logic to a dedicated, memory-optimized Go service. This shows an understanding of how to align algorithmic choices with system architecture.
Practice Problem: Redundant Connection
Let's put this into practice with another classic problem.
Problem: (LeetCode 684. Redundant Connection) You are given a graph that started as a tree with N nodes (labeled 1 to N) and had one additional edge added. The added edge creates a cycle. Find and return this redundant edge.
Example:
edges = [[1,2], [2,3], [3,4], [1,4], [1,5]]- The nodes
1, 2, 3, 4form a cycle. The edge[1,4]is the first one that closes this loop if we process edges in order. - Output:
[1,4]
Your Task:
Think about how you would solve this using the UnionFind struct we just reviewed. What condition signifies that you have found the redundant edge?
Click to see the logic and Go solution
Logic:
The core idea is to process the edges one by one. An edge is redundant if it connects two nodes that are already in the same component.
- Initialize a
UnionFinddata structure withNelements. - Iterate through the list of edges
(u, v). - For each edge, before performing a
Union, check ifuandvare already connected. You do this by callingFind(u)andFind(v). - If
Find(u) == Find(v), thenuandvare already in the same component. Adding this edge would create a cycle, so this is the redundant edge. Return it. - If they are not connected, perform
Union(u, v)to merge their components and continue to the next edge.
Go Solution:
(Note: LeetCode uses 1-based indexing for nodes, so we create a DSU of size n+1 for convenience)
func findRedundantConnection(edges [][]int) []int {
n := len(edges)
uf := NewUnionFind(n + 1) // Using the struct from earlier
for _, edge := range edges {
u, v := edge[0], edge[1]
// If u and v are already in the same set, this edge is redundant.
if uf.Find(u) == uf.Find(v) {
return edge
}
// Otherwise, union them.
uf.Union(u, v)
}
return []int{} // Should not be reached given the problem constraints
}
// Assume the UnionFind struct and its methods are defined as shown before.
Conclusion
This lesson concludes our module on core graph algorithms. We've mastered the Union-Find data structure, a specialized but extremely efficient tool for connectivity problems.
Key Takeaways:
- Purpose: Union-Find tracks and merges disjoint sets, ideal for connected components problems.
- Core Operations:
Find(to get a set's representative) andUnion(to merge sets). - Essential Optimizations: Union by Size/Rank and Path Compression are non-negotiable for achieving the near-constant amortized time complexity.
- Application: The structure allows you to process edges dynamically and answer connectivity queries far more efficiently than re-running DFS/BFS.
- System-Level Impact: As seen with Heap.io, understanding and correctly applying such data structures can lead to massive performance improvements in production systems.
Our journey now pivots to a topic you've identified as an area for growth: Dynamic Programming. In the next lesson, we will begin our deep dive by learning to identify the two fundamental properties that characterize a DP problem: overlapping subproblems and optimal substructure.