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.

Union-Find — Python template
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 True

Complexity 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.

Related LeetCode topics

Easy (1)

#ProblemDifficultyTopics
1971Find if Path Exists in GraphEasyDepth-First Search, Breadth-First Search, Union Find +1

Medium (44)

#ProblemDifficultyTopics
128Longest Consecutive SequenceMediumUnion Find, Array, Hash Table
130Surrounded RegionsMediumDepth-First Search, Breadth-First Search, Union Find +2
200Number of IslandsMediumDepth-First Search, Breadth-First Search, Union Find +2
399Evaluate DivisionMediumDepth-First Search, Breadth-First Search, Union Find +4
547Number of ProvincesMediumDepth-First Search, Breadth-First Search, Union Find +1
684Redundant ConnectionMediumDepth-First Search, Breadth-First Search, Union Find +1
695Max Area of IslandMediumDepth-First Search, Breadth-First Search, Union Find +2
721Accounts MergeMediumDepth-First Search, Breadth-First Search, Union Find +4
1584Min Cost to Connect All PointsMediumUnion Find, Graph, Array +1
261Graph Valid TreePremiumMediumDepth-First Search, Breadth-First Search, Union Find +1
323Number of Connected Components in an Undirected GraphPremiumMediumDepth-First Search, Breadth-First Search, Union Find +1
694Number of Distinct IslandsPremiumMediumDepth-First Search, Breadth-First Search, Union Find +2
737Sentence Similarity IIPremiumMediumDepth-First Search, Breadth-First Search, Union Find +3
785Is Graph Bipartite?MediumDepth-First Search, Breadth-First Search, Union Find +1
886Possible BipartitionMediumDepth-First Search, Breadth-First Search, Union Find +1
947Most Stones Removed with Same Row or ColumnMediumDepth-First Search, Union Find, Graph +1
959Regions Cut By SlashesMediumDepth-First Search, Breadth-First Search, Union Find +3
990Satisfiability of Equality EquationsMediumUnion Find, Graph, Array +1
1020Number of EnclavesMediumDepth-First Search, Breadth-First Search, Union Find +2
1061Lexicographically Smallest Equivalent StringMediumUnion Find, String
1101The Earliest Moment When Everyone Become FriendsPremiumMediumUnion Find, Array, Sorting
1102Path With Maximum Minimum ValuePremiumMediumDepth-First Search, Breadth-First Search, Union Find +4
1135Connecting Cities With Minimum CostPremiumMediumUnion Find, Graph, Minimum Spanning Tree +1
1202Smallest String With SwapsMediumDepth-First Search, Breadth-First Search, Union Find +4
1254Number of Closed IslandsMediumDepth-First Search, Breadth-First Search, Union Find +2
1258Synonymous SentencesPremiumMediumSort, Union Find, Array +3
1267Count Servers that CommunicateMediumDepth-First Search, Breadth-First Search, Union Find +3
1319Number of Operations to Make Network ConnectedMediumDepth-First Search, Breadth-First Search, Union Find +1
1361Validate Binary Tree NodesMediumTree, Depth-First Search, Breadth-First Search +3
1391Check if There is a Valid Path in a GridMediumDepth-First Search, Breadth-First Search, Union Find +2
1559Detect Cycles in 2D GridMediumDepth-First Search, Breadth-First Search, Union Find +2
1631Path With Minimum EffortMediumDepth-First Search, Breadth-First Search, Union Find +4
1722Minimize Hamming Distance After Swap OperationsMediumDepth-First Search, Union Find, Array
1905Count Sub IslandsMediumDepth-First Search, Breadth-First Search, Union Find +2
2316Count Unreachable Pairs of Nodes in an Undirected GraphMediumDepth-First Search, Breadth-First Search, Union Find +1
2368Reachable Nodes With RestrictionsMediumTree, Depth-First Search, Breadth-First Search +4
2424Longest Uploaded PrefixMediumUnion Find, Design, Binary Indexed Tree +5
2492Minimum Score of a Path Between Two CitiesMediumDepth-First Search, Breadth-First Search, Union Find +1
2658Maximum Number of Fish in a GridMediumDepth-First Search, Breadth-First Search, Union Find +2
2685Count the Number of Complete ComponentsMediumDepth-First Search, Breadth-First Search, Union Find +1
2782Number of Unique CategoriesPremiumMediumUnion Find, Counting, Interactive
2812Find the Safest Path in a GridMediumBreadth-First Search, Union Find, Array +3
2852Sum of Remoteness of All CellsPremiumMediumDepth-First Search, Breadth-First Search, Union Find +3
2948Make Lexicographically Smallest Array by Swapping ElementsMediumUnion Find, Array, Sorting

Hard (38)

#ProblemDifficultyTopics
352Data Stream as Disjoint IntervalsHardUnion Find, Design, Hash Table +3
685Redundant Connection IIHardDepth-First Search, Breadth-First Search, Union Find +1
778Swim in Rising WaterHardDepth-First Search, Breadth-First Search, Union Find +4
305Number of Islands IIPremiumHardUnion Find, Array, Hash Table
711Number of Distinct Islands IIPremiumHardDepth-First Search, Breadth-First Search, Union Find +2
765Couples Holding HandsHardGreedy, Depth-First Search, Breadth-First Search +2
803Bricks Falling When HitHardUnion Find, Array, Matrix
827Making A Large IslandHardDepth-First Search, Breadth-First Search, Union Find +2
839Similar String GroupsHardDepth-First Search, Breadth-First Search, Union Find +3
924Minimize Malware SpreadHardDepth-First Search, Breadth-First Search, Union Find +3
928Minimize Malware Spread IIHardDepth-First Search, Breadth-First Search, Union Find +3
952Largest Component Size by Common FactorHardUnion Find, Array, Hash Table +2
1168Optimize Water Distribution in a VillagePremiumHardUnion Find, Graph, Minimum Spanning Tree +1
1489Find Critical and Pseudo-Critical Edges in Minimum Spanning TreeHardUnion Find, Graph, Minimum Spanning Tree +2
1569Number of Ways to Reorder Array to Get Same BSTHardTree, Union Find, Binary Search Tree +7
1579Remove Max Number of Edges to Keep Graph Fully TraversableHardUnion Find, Graph
1627Graph Connectivity With ThresholdHardUnion Find, Array, Math +1
1632Rank Transform of a MatrixHardUnion Find, Graph, Topological Sort +3
1697Checking Existence of Edge Length Limited PathsHardUnion Find, Graph, Array +2
1724Checking Existence of Edge Length Limited Paths IIPremiumHardUnion Find, Graph, Minimum Spanning Tree
1970Last Day Where You Can Still CrossHardDepth-First Search, Breadth-First Search, Union Find +3
1998GCD Sort of an ArrayHardUnion Find, Array, Math +2
2003Smallest Missing Genetic Value in Each SubtreeHardTree, Depth-First Search, Union Find +1
2076Process Restricted Friend RequestsHardUnion Find, Graph
2092Find All People With SecretHardDepth-First Search, Breadth-First Search, Union Find +2
2157Groups of StringsHardBit Manipulation, Union Find, String
2204Distance to a Cycle in Undirected GraphPremiumHardDepth-First Search, Breadth-First Search, Union Find +1
2307Check for Contradictions in EquationsPremiumHardDepth-First Search, Union Find, Graph +1
2334Subarray With Elements Greater Than Varying ThresholdHardStack, Union Find, Array +1
2371Minimize Maximum Value in a GridPremiumHardUnion Find, Graph, Topological Sort +3
2382Maximum Segment Sum After RemovalsHardUnion Find, Array, Ordered Set +1
2421Number of Good PathsHardTree, Union Find, Graph +3
2493Divide Nodes Into the Maximum Number of GroupsHardDepth-First Search, Breadth-First Search, Union Find +1
2503Maximum Number of Points From Grid QueriesHardBreadth-First Search, Union Find, Array +4
2573Find the String with LCPHardGreedy, Union Find, Array +3
2612Minimum Reverse OperationsHardBreadth-First Search, Union Find, Array +2
2617Minimum Number of Visited Cells in a GridHardStack, Breadth-First Search, Union Find +5
2709Greatest Common Divisor TraversalHardUnion 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.