Union-Find & Disjoint Set Interview Problems: Master the Pattern
Master Union-Find (Disjoint Set Union) for coding interviews.
20+ years shipping production code across the stack, with years spent interviewing engineers. Everything here is grounded in real deployments.
- ✓Basic understanding of graphs and connectivity
- ✓Familiarity with recursion and arrays
- ✓Knowledge of time complexity analysis
- Union-Find (DSU) tracks connected components in a graph.
- Supports two operations: find (with path compression) and union (by rank/size).
- Time complexity: nearly O(α(n)) per operation, where α is the inverse Ackermann function.
- Common interview problems: Number of Islands, Accounts Merge, Redundant Connection, etc.
- Key to solving: identify when you need to group elements dynamically.
Imagine you have a group of people at a party, and you want to know who is friends with whom. Each person starts alone. When two people become friends, you connect them. Union-Find is like a system that keeps track of these friend groups. If you ask 'Are these two people in the same friend group?' it can answer quickly. It's like a social network for sets.
Imagine you're building a social network feature that suggests friends of friends. Or you're detecting connected components in an image. Or you're solving a coding interview problem like 'Number of Islands' or 'Accounts Merge'. All these tasks share a common need: efficiently managing and querying dynamic connectivity. This is where Union-Find, also known as Disjoint Set Union (DSU), shines.
Union-Find is a data structure that tracks a set of elements partitioned into disjoint (non-overlapping) subsets. It provides two primary operations: find (determine which subset a particular element belongs to) and union (merge two subsets into one). With optimizations like path compression and union by rank, these operations run in nearly constant time, making it a powerful tool for many graph and connectivity problems.
In this guide, you'll learn the core concepts, see how to implement DSU in Python and Java, and walk through classic interview problems step by step. We'll also cover common mistakes, debugging tips, and real-world production incidents where Union-Find saved the day. By the end, you'll be ready to tackle any Union-Find problem that comes your way.
What is Union-Find?
Union-Find, also known as Disjoint Set Union (DSU), is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets. It supports two primary operations: - Find: Determine which subset a particular element belongs to. This is typically used to check if two elements are in the same subset. - Union: Merge two subsets into a single subset.
The structure is initialized with each element in its own subset. Over time, unions connect elements, forming larger sets. The find operation can be optimized with path compression, where after finding the root of an element, we update the parent pointers along the path to point directly to the root, flattening the tree. The union operation can be optimized with union by rank or union by size, where we attach the smaller tree under the root of the larger tree to keep the tree shallow.
With these optimizations, the amortized time complexity per operation is nearly O(α(n)), where α is the inverse Ackermann function, which grows extremely slowly and is effectively constant for all practical input sizes.
Classic Problem: Number of Islands
The Number of Islands problem is a classic application of Union-Find. Given a 2D grid of '1's (land) and '0's (water), count the number of islands (connected groups of '1's). You can solve this using DFS/BFS, but Union-Find is also elegant.
Approach: Treat each cell as an element. For each '1', union it with its right and down neighbors if they are also '1'. After processing all cells, count the number of distinct roots among '1's.
Time complexity: O(m n α(mn)), where m and n are grid dimensions. Space: O(m n) for the parent array.
Let's implement this in Python.
Problem: Accounts Merge
Given a list of accounts where each account has a name and a list of emails, merge accounts that share common emails. The output should have one account per person (name and sorted emails).
This problem is a classic Union-Find application. We treat each email as an element. For each account, we union the first email with all other emails in that account. After processing all accounts, we group emails by their root. Then for each group, we take the name from any account (they all have the same name) and output sorted emails.
Time complexity: O(N * α(N)) where N is total number of emails. Space: O(N).
Problem: Redundant Connection
In this problem, you are given a graph that started as a tree (n nodes, n-1 edges) but one extra edge was added, creating a cycle. Find the edge that can be removed to make it a tree again. If multiple edges can be removed, return the one that appears last in the input.
Union-Find is perfect here: iterate through edges, for each edge (u, v), if u and v are already in the same set, this edge creates a cycle and is the redundant connection. Otherwise, union them.
Time complexity: O(n * α(n)). Space: O(n).
Problem: Longest Consecutive Sequence
Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, [100, 4, 200, 1, 3, 2] returns 4 (sequence [1,2,3,4]).
Union-Find can solve this: treat each number as an element. For each number, if num-1 exists, union them; if num+1 exists, union them. Then find the size of the largest set.
Alternatively, use a hash set for O(n) time. But Union-Find is a valid approach.
Time complexity: O(n * α(n)). Space: O(n).
Problem: Satisfiability of Equality Equations
Given an array of equations like 'a==b' and 'a!=b', determine if all equations can be satisfied. This is a classic Union-Find problem: first process all '==' equations to union variables, then check '!=' equations: if two variables are in the same set, return false.
Time complexity: O(n * α(26)) since only lowercase letters. Space: O(26).
Advanced: Dynamic Connectivity with Offline Queries
Sometimes you need to answer connectivity queries after a series of union operations. Union-Find can handle this online. But what if you have to answer queries after some unions are undone? That's harder. However, for offline queries (all queries known in advance), you can use Union-Find with a divide-and-conquer approach (DSU with rollback). This is an advanced topic.
For interview purposes, focus on the standard Union-Find. But knowing that Union-Find can be extended to support undo operations (by storing stack of changes) can impress interviewers.
Time complexity: O((n+q) log n) for offline queries with rollback.
The Social Network Friend Suggestion Outage
find() led to deep trees, causing union to miss connections in concurrent updates.- Always implement path compression for near-constant time operations.
- Use union by rank or size to keep trees balanced.
- Be careful with concurrent modifications; consider using locks or atomic operations.
- Test with large, dynamic datasets to catch performance issues.
- Monitor
find()depth in production to detect inefficiencies.
find() operationsfind() depth.print(parent)trace find(5) manually| File | Command / Code | Purpose |
|---|---|---|
| union_find.py | class UnionFind: | What is Union-Find? |
| num_islands.py | class UnionFind: | Classic Problem |
| accounts_merge.py | def accountsMerge(accounts): | Problem |
| redundant_connection.py | def findRedundantConnection(edges): | Problem |
| longest_consecutive.py | def longestConsecutive(nums): | Problem |
| equations_possible.py | def equationsPossible(equations): | Problem |
| dsu_rollback.py | class DSUWithRollback: | Advanced |
Key takeaways
Common mistakes to avoid
5 patternsNot implementing path compression
Forgetting to update rank/size during union
Using union by rank but not initializing rank array
Not handling 1-indexed nodes correctly
Using recursion in find for very deep trees
Interview Questions on This Topic
Implement Union-Find with path compression and union by rank.
Frequently Asked Questions
20+ years shipping production code across the stack, with years spent interviewing engineers. Everything here is grounded in real deployments.
That's Coding Patterns. Mark it forged?
3 min read · try the examples if you haven't