Pattern 19 of 22

Union-Find Pattern: Template + 83 LeetCode Problems

Merge groups and ask whether two things are connected, both in near-constant time.

Easy
1
Medium
44
Hard
38

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.

PythonUnion-Find 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.

Eyes only

Meet the union-find problem you did not practise.

In the live round, Stealth Interview reads the 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 says. It's a desktop app for macOS and Windows, invisible to screen sharing.

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)

Easy problems
No.Problem
1971Find if Path Exists in Graph

Medium (44)

Medium problems
No.Problem
0128Longest Consecutive Sequence
0130Surrounded Regions
0200Number of Islands
0399Evaluate Division
0547Number of Provinces
0684Redundant Connection
0695Max Area of Island
0721Accounts Merge
1584Min Cost to Connect All Points
0261Graph Valid TreePremium
0323Number of Connected Components in an Undirected GraphPremium
0694Number of Distinct IslandsPremium
0737Sentence Similarity IIPremium
0785Is Graph Bipartite?
0886Possible Bipartition
0947Most Stones Removed with Same Row or Column
0959Regions Cut By Slashes
0990Satisfiability of Equality Equations
1020Number of Enclaves
1061Lexicographically Smallest Equivalent String
1101The Earliest Moment When Everyone Become FriendsPremium
1102Path With Maximum Minimum ValuePremium
1135Connecting Cities With Minimum CostPremium
1202Smallest String With Swaps
1254Number of Closed Islands
1258Synonymous SentencesPremium
1267Count Servers that Communicate
1319Number of Operations to Make Network Connected
1361Validate Binary Tree Nodes
1391Check if There is a Valid Path in a Grid
1559Detect Cycles in 2D Grid
1631Path With Minimum Effort
1722Minimize Hamming Distance After Swap Operations
1905Count Sub Islands
2316Count Unreachable Pairs of Nodes in an Undirected Graph
2368Reachable Nodes With Restrictions
2424Longest Uploaded Prefix
2492Minimum Score of a Path Between Two Cities
2658Maximum Number of Fish in a Grid
2685Count the Number of Complete Components
2782Number of Unique CategoriesPremium
2812Find the Safest Path in a Grid
2852Sum of Remoteness of All CellsPremium
2948Make Lexicographically Smallest Array by Swapping Elements

Hard (38)

Hard problems
No.Problem
0352Data Stream as Disjoint Intervals
0685Redundant Connection II
0778Swim in Rising Water
0305Number of Islands IIPremium
0711Number of Distinct Islands IIPremium
0765Couples Holding Hands
0803Bricks Falling When Hit
0827Making A Large Island
0839Similar String Groups
0924Minimize Malware Spread
0928Minimize Malware Spread II
0952Largest Component Size by Common Factor
1168Optimize Water Distribution in a VillagePremium
1489Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
1569Number of Ways to Reorder Array to Get Same BST
1579Remove Max Number of Edges to Keep Graph Fully Traversable
1627Graph Connectivity With Threshold
1632Rank Transform of a Matrix
1697Checking Existence of Edge Length Limited Paths
1724Checking Existence of Edge Length Limited Paths IIPremium
1970Last Day Where You Can Still Cross
1998GCD Sort of an Array
2003Smallest Missing Genetic Value in Each Subtree
2076Process Restricted Friend Requests
2092Find All People With Secret
2157Groups of Strings
2204Distance to a Cycle in Undirected GraphPremium
2307Check for Contradictions in EquationsPremium
2334Subarray With Elements Greater Than Varying Threshold
2371Minimize Maximum Value in a GridPremium
2382Maximum Segment Sum After Removals
2421Number of Good Paths
2493Divide Nodes Into the Maximum Number of Groups
2503Maximum Number of Points From Grid Queries
2573Find the String with LCP
2612Minimum Reverse Operations
2617Minimum Number of Visited Cells in a Grid
2709Greatest Common Divisor Traversal

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.