Union-Find Pattern: Template + 83 LeetCode Problems
Merge groups and ask whether two things are connected, both in near-constant time.
- 1 Easy
- 44 Medium
- 38 Hard
- O(α(n)) amortised per operation time
What the union-find pattern is
Union-Find — a disjoint set union, or DSU — maintains a partition of elements into groups under two operations: merge two groups, and ask which group an element belongs to. Each group is a tree whose root is its name, so the question "are these connected?" reduces to "do they have the same root?". Two optimisations make it fast enough to disappear from the complexity analysis. Path compression flattens the tree on the way back from a lookup, pointing every node visited straight at the root. Union by size or rank always hangs the smaller tree under the larger one, so no chain gets long in the first place. Together they give an amortised inverse-Ackermann cost per operation, effectively constant. Reach for it instead of a graph traversal when edges arrive one at a time and the question is about connectivity as they arrive — that is the case a DFS cannot answer without re-running.
When to use it
- Edges or merges arrive incrementally and you must answer connectivity questions between them.
- You need the number of connected components, or the size of the component containing a node.
- The problem asks whether adding an edge creates a cycle — union returning false is exactly that.
- You are building a minimum spanning tree with Kruskal's algorithm.
- Grouping is transitive: accounts that share an email, equations that chain equalities, stones in the same row or column.
The union-find template in Python
The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 83 problems listed below.
class DSU:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
def find(self, x):
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]] # path halving
x = self.parent[x]
return x
def union(self, a, b):
root_a, root_b = self.find(a), self.find(b)
if root_a == root_b:
return False # already together: this edge is a cycle
if self.size[root_a] < self.size[root_b]:
root_a, root_b = root_b, root_a # hang the smaller tree under the larger
self.parent[root_b] = root_a
self.size[root_a] += self.size[root_b]
return TrueComplexity characteristics
- Time
- O(α(n)) amortised per operation
- Auxiliary space
- O(n)
With path compression and union by size applied together, m operations over n elements cost O(m·α(n)), where α is the inverse Ackermann function and is at most 4 for any n that fits in memory — effectively constant, which is why union-find usually disappears from the complexity of the algorithm using it. Either optimisation on its own is materially worse: union by size alone leaves O(log n) per operation. The space is the parent and size arrays.
All 83 union-find LeetCode problems
Every problem in the library the union-find pattern applies to, grouped by LeetCode's own difficulty rating. 66 of the 83 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.
Easy (1)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 1971 | Find if Path Exists in Graph | Easy | Depth-First Search, Breadth-First Search, Union Find +1 |
Medium (44)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 128 | Longest Consecutive Sequence | Medium | Union Find, Array, Hash Table |
| 130 | Surrounded Regions | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 200 | Number of Islands | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 399 | Evaluate Division | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 547 | Number of Provinces | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 684 | Redundant Connection | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 695 | Max Area of Island | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 721 | Accounts Merge | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 1584 | Min Cost to Connect All Points | Medium | Union Find, Graph, Array +1 |
| 261 | Graph Valid TreePremium | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 323 | Number of Connected Components in an Undirected GraphPremium | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 694 | Number of Distinct IslandsPremium | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 737 | Sentence Similarity IIPremium | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 785 | Is Graph Bipartite? | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 886 | Possible Bipartition | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 947 | Most Stones Removed with Same Row or Column | Medium | Depth-First Search, Union Find, Graph +1 |
| 959 | Regions Cut By Slashes | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 990 | Satisfiability of Equality Equations | Medium | Union Find, Graph, Array +1 |
| 1020 | Number of Enclaves | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1061 | Lexicographically Smallest Equivalent String | Medium | Union Find, String |
| 1101 | The Earliest Moment When Everyone Become FriendsPremium | Medium | Union Find, Array, Sorting |
| 1102 | Path With Maximum Minimum ValuePremium | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 1135 | Connecting Cities With Minimum CostPremium | Medium | Union Find, Graph, Minimum Spanning Tree +1 |
| 1202 | Smallest String With Swaps | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 1254 | Number of Closed Islands | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1258 | Synonymous SentencesPremium | Medium | Sort, Union Find, Array +3 |
| 1267 | Count Servers that Communicate | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 1319 | Number of Operations to Make Network Connected | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 1361 | Validate Binary Tree Nodes | Medium | Tree, Depth-First Search, Breadth-First Search +3 |
| 1391 | Check if There is a Valid Path in a Grid | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1559 | Detect Cycles in 2D Grid | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 1631 | Path With Minimum Effort | Medium | Depth-First Search, Breadth-First Search, Union Find +4 |
| 1722 | Minimize Hamming Distance After Swap Operations | Medium | Depth-First Search, Union Find, Array |
| 1905 | Count Sub Islands | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 2316 | Count Unreachable Pairs of Nodes in an Undirected Graph | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2368 | Reachable Nodes With Restrictions | Medium | Tree, Depth-First Search, Breadth-First Search +4 |
| 2424 | Longest Uploaded Prefix | Medium | Union Find, Design, Binary Indexed Tree +5 |
| 2492 | Minimum Score of a Path Between Two Cities | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2658 | Maximum Number of Fish in a Grid | Medium | Depth-First Search, Breadth-First Search, Union Find +2 |
| 2685 | Count the Number of Complete Components | Medium | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2782 | Number of Unique CategoriesPremium | Medium | Union Find, Counting, Interactive |
| 2812 | Find the Safest Path in a Grid | Medium | Breadth-First Search, Union Find, Array +3 |
| 2852 | Sum of Remoteness of All CellsPremium | Medium | Depth-First Search, Breadth-First Search, Union Find +3 |
| 2948 | Make Lexicographically Smallest Array by Swapping Elements | Medium | Union Find, Array, Sorting |
Hard (38)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 352 | Data Stream as Disjoint Intervals | Hard | Union Find, Design, Hash Table +3 |
| 685 | Redundant Connection II | Hard | Depth-First Search, Breadth-First Search, Union Find +1 |
| 778 | Swim in Rising Water | Hard | Depth-First Search, Breadth-First Search, Union Find +4 |
| 305 | Number of Islands IIPremium | Hard | Union Find, Array, Hash Table |
| 711 | Number of Distinct Islands IIPremium | Hard | Depth-First Search, Breadth-First Search, Union Find +2 |
| 765 | Couples Holding Hands | Hard | Greedy, Depth-First Search, Breadth-First Search +2 |
| 803 | Bricks Falling When Hit | Hard | Union Find, Array, Matrix |
| 827 | Making A Large Island | Hard | Depth-First Search, Breadth-First Search, Union Find +2 |
| 839 | Similar String Groups | Hard | Depth-First Search, Breadth-First Search, Union Find +3 |
| 924 | Minimize Malware Spread | Hard | Depth-First Search, Breadth-First Search, Union Find +3 |
| 928 | Minimize Malware Spread II | Hard | Depth-First Search, Breadth-First Search, Union Find +3 |
| 952 | Largest Component Size by Common Factor | Hard | Union Find, Array, Hash Table +2 |
| 1168 | Optimize Water Distribution in a VillagePremium | Hard | Union Find, Graph, Minimum Spanning Tree +1 |
| 1489 | Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree | Hard | Union Find, Graph, Minimum Spanning Tree +2 |
| 1569 | Number of Ways to Reorder Array to Get Same BST | Hard | Tree, Union Find, Binary Search Tree +7 |
| 1579 | Remove Max Number of Edges to Keep Graph Fully Traversable | Hard | Union Find, Graph |
| 1627 | Graph Connectivity With Threshold | Hard | Union Find, Array, Math +1 |
| 1632 | Rank Transform of a Matrix | Hard | Union Find, Graph, Topological Sort +3 |
| 1697 | Checking Existence of Edge Length Limited Paths | Hard | Union Find, Graph, Array +2 |
| 1724 | Checking Existence of Edge Length Limited Paths IIPremium | Hard | Union Find, Graph, Minimum Spanning Tree |
| 1970 | Last Day Where You Can Still Cross | Hard | Depth-First Search, Breadth-First Search, Union Find +3 |
| 1998 | GCD Sort of an Array | Hard | Union Find, Array, Math +2 |
| 2003 | Smallest Missing Genetic Value in Each Subtree | Hard | Tree, Depth-First Search, Union Find +1 |
| 2076 | Process Restricted Friend Requests | Hard | Union Find, Graph |
| 2092 | Find All People With Secret | Hard | Depth-First Search, Breadth-First Search, Union Find +2 |
| 2157 | Groups of Strings | Hard | Bit Manipulation, Union Find, String |
| 2204 | Distance to a Cycle in Undirected GraphPremium | Hard | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2307 | Check for Contradictions in EquationsPremium | Hard | Depth-First Search, Union Find, Graph +1 |
| 2334 | Subarray With Elements Greater Than Varying Threshold | Hard | Stack, Union Find, Array +1 |
| 2371 | Minimize Maximum Value in a GridPremium | Hard | Union Find, Graph, Topological Sort +3 |
| 2382 | Maximum Segment Sum After Removals | Hard | Union Find, Array, Ordered Set +1 |
| 2421 | Number of Good Paths | Hard | Tree, Union Find, Graph +3 |
| 2493 | Divide Nodes Into the Maximum Number of Groups | Hard | Depth-First Search, Breadth-First Search, Union Find +1 |
| 2503 | Maximum Number of Points From Grid Queries | Hard | Breadth-First Search, Union Find, Array +4 |
| 2573 | Find the String with LCP | Hard | Greedy, Union Find, Array +3 |
| 2612 | Minimum Reverse Operations | Hard | Breadth-First Search, Union Find, Array +2 |
| 2617 | Minimum Number of Visited Cells in a Grid | Hard | Stack, Breadth-First Search, Union Find +5 |
| 2709 | Greatest Common Divisor Traversal | Hard | Union Find, Array, Math +1 |
Related patterns
Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.
Union-Find pattern FAQ
What is the union-find pattern?
Union-Find — a disjoint set union, or DSU — maintains a partition of elements into groups under two operations: merge two groups, and ask which group an element belongs to.
How many LeetCode problems use the union-find pattern?
This page lists 83 LeetCode problems that the union-find pattern applies to: 1 Easy, 44 Medium and 38 Hard. 66 of them carry a complete Python solution with complexity analysis.
What is the time complexity of the union-find pattern?
O(α(n)) amortised per operation time and O(n) space. With path compression and union by size applied together, m operations over n elements cost O(m·α(n)), where α is the inverse Ackermann function and is at most 4 for any n that fits in memory — effectively constant, which is why union-find usually disappears from the complexity of the algorithm using it. Either optimisation on its own is materially worse: union by size alone leaves O(log n) per operation. The space is the parent and size arrays.
When should I use the union-find pattern in an interview?
Edges or merges arrive incrementally and you must answer connectivity questions between them. You need the number of connected components, or the size of the component containing a node.
Which union-find problem should I start with?
LeetCode 1971. Find if Path Exists in Graph is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.
What patterns are related to union-find?
Depth-First Search, Breadth-First Search, Topological Sort, Sorting. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.
More ways in: all 22 patterns, the curated study lists, or the full problem list.
Meet the union-find problem you did not practise
Stealth Interview is a desktop app for macOS and Windows. It reads the coding problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer is saying — while staying invisible to screen sharing.