Union-Find (Disjoint Set)
Data StructuresConnectivity, cycle detection, and clustering in undirected networks
83 problems·1 Easy·47 Medium·35 Hard
Pattern Study Guide & Cheat Sheet▼
Disjoint Set Union (DSU) tracks partitions and connectivity of elements, merging groups and querying whether two elements share a component in near-constant O(α(N)) time.
Core Invariant: Maintain representative parent pointers. With Path Compression (`parent[x] = find(parent[x])`) and Union by Rank, tree depth remains <= 4 for all practical universe scales (inverse Ackermann α(N)).
Recognize it (Keywords & Signals)
- Connected components in an undirected network
- Redundant connection / cycle detection in undirected graph
- Number of provinces / islands / friend circles
- Graph valid tree (exactly n - 1 edges and 1 connected component)
- Minimum Spanning Tree (Kruskal's algorithm)
When NOT to use
Directed graphs (DSU cannot handle edge directions; use Topological Sort or Tarjan / Kosaraju).
How to solve (Step-by-step)
- 1.Initialize `parent = list(range(n))` and `rank = [1] * n`.
- 2.Implement `find(x)`: recursively find root while flattening tree (`parent[x] = find(parent[x])`).
- 3.Implement `union(x, y)`: find roots `rx = find(x)`, `ry = find(y)`. If equal, they already connect (cycle detected!).
- 4.If unequal, attach smaller rank root under larger rank root, and decrement component count.
- 5.Return True if merged, False if already connected.
Watch for (Interview Traps)
- Comparing raw node IDs instead of representative roots (`x == y` instead of `find(x) == find(y)`)
- Omitting path compression: operations degenerate to O(N) linear chains without it
- Using DSU on directed graphs where edge orientation matters
Disjoint Set Union (DSU) with Path Compression & Rank
class UnionFind:
def __init__(self, size: int):
self.parent = list(range(size))
self.rank = [1] * size
self.components = size
def find(self, x: int) -> int:
if self.parent[x] != x:
# Path compression: flatten path directly to root
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x: int, y: int) -> bool:
root_x, root_y = self.find(x), self.find(y)
if root_x == root_y:
return False # Already in same set (cycle detected!)
# Union by rank: attach smaller tree under larger tree
if self.rank[root_x] > self.rank[root_y]:
self.parent[root_y] = root_x
elif self.rank[root_x] < self.rank[root_y]:
self.parent[root_x] = root_y
else:
self.parent[root_y] = root_x
self.rank[root_x] += 1
self.components -= 1
return True- Cost
- O(α(N)) ≈ O(1) amortized per operation · O(N) for parent and rank arrays (Inverse Ackermann α(N) never exceeds 4 for any practical input size.)
Canonical problems
#547 Number of Provinces: Union cities with direct flights; return final component count
#684 Redundant Connection: First edge where union returns False creates the cycle
#261 Graph Valid Tree: Must have exactly n - 1 edges and 1 connected component
#128 Longest Consecutive Sequence: Union adjacent numbers x and x+1
⌘K
Medium·44 companies·Max freq 100%·Acc 47.2%
Wissen TechnologyWissen TechnologyNeetCode 150+41
Medium·25 companies·Max freq 100%·Acc 64.4%
Tower Research CapitalTower Research CapitalUrban Company+22
Medium·12 companies·Max freq 100%·Acc 71.3%
DirectiNeetCode 150NeetCode 150+9
Medium·11 companies·Max freq 100%·Acc 66.9%
Akuna CapitalPhonePeIBM+8
Medium·10 companies·Max freq 100%·Acc 65.1%
XGeneral MotorsX+7
Medium·7 companies·Max freq 100%·Acc 0.5%
Sumo LogicSumo LogicCleverTap+4
Hard·7 companies·Max freq 63%·Acc 0.6%
CitadelSquarepoint CapitalPalo Alto Networks+4
Hard·6 companies·Max freq 75%·Acc 68.2%
DE ShawTuringGoogle+3
Medium·6 companies·Max freq 75%·Acc 60.3%
PhonePeAtlassianIBM+3
Hard·6 companies·Max freq 63%·Acc 66.9%
UberAccentureGoogle+3
Medium·5 companies·Max freq 68%·Acc 81.1%
ClouderaAmazonMeta+2
Medium·5 companies·Max freq 63%·Acc 0.5%
SnapSnapAmazon+2
Hard·5 companies·Max freq 50%·Acc 0.7%
UberDE ShawMeta+2
Medium·5 companies·Max freq 38%·Acc 70.7%
GoogleBloombergMeta+2
Hard·4 companies·Max freq 100%·Acc 45.8%
instabaseTikTokGoogle+1
Medium·4 companies·Max freq 79%·Acc 0.7%
Sumo LogicSumo LogicGoogle+1
Medium·4 companies·Max freq 63%·Acc 43.7%
SalesforceAppleMicrosoft+1
Medium·4 companies·Max freq 50%·Acc 54.8%
TikTokGoogleMeta+1
Hard·4 companies·Max freq 38%·Acc 66.6%
UberAmazonMeta+1
Hard·4 companies·Max freq 38%·Acc 45.1%
InfosysAmazonMicrosoft+1
Medium·4 companies·Max freq 16%·Acc 80.8%
MicrosoftMetaAmazon+1
Hard·3 companies·Max freq 100%·Acc 24.0%
HuaweiWorldQuantDE Shaw
Medium·3 companies·Max freq 100%·Acc 64.5%
RobinhoodSamsungGoogle
Medium·3 companies·Max freq 91%·Acc 66.1%
ExpediaUberGoogle
Medium·3 companies·Max freq 25%·Acc 50.1%
UberGoogleMeta
Hard·3 companies·Max freq 25%·Acc 63.4%
UberGoogleMicrosoft
Hard·3 companies·Max freq 13%·Acc 66.2%
AmazonMicrosoftGoogle
Medium·2 companies·Max freq 79%·Acc 56.2%
IntuitGoogle
Hard·2 companies·Max freq 75%·Acc 51.6%
Oscar HealthGoogle
# | Problem | Difficulty | Top Companies↓ | Frequency | Acceptance | |
|---|---|---|---|---|---|---|
| #200 | Number of Islands ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix | Medium | 100% | 64.7% | ||
| #128 | Longest Consecutive Sequence ArrayHash TableUnion-Find | Medium | 100% | 47.2% | ||
| #399 | Evaluate Division ArrayStringDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryShortest PathBellman–Ford AlgorithmFloyd–Warshall Algorithm | Medium | 100% | 64.4% | ||
| #695 | Max Area of Island ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix | Medium | 100% | 74.1% | ||
| #721 | Accounts Merge ArrayHash TableStringDepth-First SearchBreadth-First SearchUnion-FindSorting | Medium | 83% | 61.6% | ||
| #130 | Surrounded Regions ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix | Medium | 87% | 0.5% | ||
| #694 | Number of Distinct Islands ArrayHash TableDepth-First SearchBreadth-First SearchUnion-FindSortingMatrixHash Function | Medium | 92% | 62.9% | ||
| #1584 | Min Cost to Connect All Points ArrayUnion-FindGraph TheoryMinimum Spanning TreePrim's AlgorithmKruskal's AlgorithmBorůvka's Algorithm | Medium | 100% | 71.3% | ||
| #886 | Possible Bipartition Depth-First SearchBreadth-First SearchUnion-FindGraph TheoryGraph ColoringBipartite Graph | Medium | 75% | 52.8% | ||
| #261 | Graph Valid Tree Depth-First SearchBreadth-First SearchUnion-FindGraph Theory | Medium | 100% | 50.1% | ||
| #1319 | Number of Operations to Make Network Connected Depth-First SearchBreadth-First SearchUnion-FindGraph Theory | Medium | 100% | 66.9% | ||
| #785 | Is Graph Bipartite? Depth-First SearchBreadth-First SearchUnion-FindGraph TheoryGraph ColoringBipartite Graph | Medium | 88% | 59.6% | ||
| #778 | Swim in Rising Water ArrayBinary SearchDepth-First SearchBreadth-First SearchUnion-FindMinimaxHeap (Priority Queue)MatrixDijkstra's Algorithm | Hard | 78% | 68.0% | ||
| #684 | Redundant Connection Depth-First SearchBreadth-First SearchUnion-FindGraph Theory | Medium | 75% | 0.7% | ||
| #323 | Number of Connected Components in an Undirected Graph Depth-First SearchBreadth-First SearchUnion-FindGraph Theory | Medium | 100% | 65.1% | ||
| #924 | Minimize Malware Spread ArrayHash TableDepth-First SearchBreadth-First SearchUnion-FindGraph Theory | Hard | 100% | 43.3% | ||
| #1202 | Smallest String With Swaps ArrayHash TableStringDepth-First SearchBreadth-First SearchUnion-FindSorting | Medium | 100% | 60.8% | ||
| #305 | Number of Islands II ArrayHash TableUnion-Find | Hard | 90% | 40.7% | ||
| #547 | Number of Provinces Depth-First SearchBreadth-First SearchUnion-FindGraph Theory | Medium | 100% | 70.7% | ||
| #1631 | Path With Minimum Effort ArrayBinary SearchDepth-First SearchBreadth-First SearchUnion-FindHeap (Priority Queue)MatrixDijkstra's Algorithm | Medium | 67% | 63.6% | ||
| #2812 | Find the Safest Path in a Grid ArrayBinary SearchBreadth-First SearchUnion-FindHeap (Priority Queue)Matrix | Medium | 62% | 57.2% | ||
| #990 | Satisfiability of Equality Equations ArrayStringUnion-FindGraph Theory | Medium | 100% | 0.5% | ||
| #3607 | Power Grid Maintenance ArrayHash TableDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryHeap (Priority Queue)Ordered Set | Medium | 75% | 56.1% | ||
| #765 | Couples Holding Hands GreedyDepth-First SearchBreadth-First SearchUnion-FindGraph Theory | Hard | 63% | 0.6% | ||
| #1559 | Detect Cycles in 2D Grid ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix | Medium | 100% | 63.4% | ||
| #3108 | Minimum Cost Walk in Weighted Graph ArrayBit ManipulationUnion-FindGraph Theory | Hard | 75% | 68.2% | ||
| #2948 | Make Lexicographically Smallest Array by Swapping Elements ArrayUnion-FindSorting | Medium | 75% | 60.3% | ||
| #2493 | Divide Nodes Into the Maximum Number of Groups Depth-First SearchBreadth-First SearchUnion-FindGraph Theory | Hard | 63% | 66.9% | ||
| #1020 | Number of Enclaves ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix | Medium | 27% | 72.0% | ||
| #1267 | Count Servers that Communicate ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrixCounting | Medium | 25% | 73.5% | ||
| #1061 | Lexicographically Smallest Equivalent String StringUnion-Find | Medium | 68% | 81.1% | ||
| #2316 | Count Unreachable Pairs of Nodes in an Undirected Graph Depth-First SearchBreadth-First SearchUnion-FindGraph Theory | Medium | 63% | 0.5% | ||
| #1579 | Remove Max Number of Edges to Keep Graph Fully Traversable Union-FindGraph Theory | Hard | 50% | 0.7% | ||
| #839 | Similar String Groups ArrayHash TableStringDepth-First SearchBreadth-First SearchUnion-Find | Hard | 38% | 56.4% | ||
| #1971 | Find if Path Exists in Graph Depth-First SearchBreadth-First SearchUnion-FindGraph Theory | Easy | 38% | 55.5% | ||
| #1254 | Number of Closed Islands ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix | Medium | 38% | 67.2% | ||
| #3532 | Path Existence Queries in a Graph I ArrayHash TableBinary SearchUnion-FindGraph Theory | Medium | 38% | 70.7% | ||
| #1258 | Synonymous Sentences ArrayHash TableStringBacktrackingSortUnion-Find | Medium | 100% | 0.6% | ||
| #2334 | Subarray With Elements Greater Than Varying Threshold ArrayStackUnion-FindMonotonic Stack | Hard | 100% | 45.8% | ||
| #803 | Bricks Falling When Hit ArrayUnion-FindMatrix | Hard | 88% | 37.5% | ||
| #1722 | Minimize Hamming Distance After Swap Operations ArrayDepth-First SearchUnion-Find | Medium | 79% | 0.7% | ||
| #3613 | Minimize Maximum Component Cost Binary SearchUnion-FindGraph TheorySorting | Medium | 63% | 43.7% | ||
| #737 | Sentence Similarity II ArrayHash TableStringDepth-First SearchBreadth-First SearchUnion-Find | Medium | 50% | 51.4% | ||
| #298 | Binary Tree Longest Consecutive Sequence TreeDepth-First SearchBinary TreeDP on Trees | Medium | 50% | 54.8% | ||
| #1970 | Last Day Where You Can Still Cross ArrayBinary SearchDepth-First SearchBreadth-First SearchUnion-FindMatrix | Hard | 41% | 68.7% | ||
| #1489 | Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree Union-FindGraph TheorySortingMinimum Spanning TreeStrongly Connected ComponentPrim's AlgorithmKruskal's AlgorithmBorůvka's Algorithm | Hard | 38% | 66.6% | ||
| #3666 | Minimum Operations to Equalize Binary String MathStringBreadth-First SearchUnion-FindOrdered Set | Hard | 38% | 45.1% | ||
| #2685 | Count the Number of Complete Components Depth-First SearchBreadth-First SearchUnion-FindGraph Theory | Medium | 16% | 80.8% | ||
| #2658 | Maximum Number of Fish in a Grid ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix | Medium | 13% | 70.3% | ||
| #2617 | Minimum Number of Visited Cells in a Grid ArrayDynamic ProgrammingStackBreadth-First SearchUnion-FindHeap (Priority Queue)MatrixMonotonic Stack | Hard | 100% | 24.0% | ||
| #1391 | Check if There is a Valid Path in a Grid ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix | Medium | 100% | 64.5% | ||
| #1101 | The Earliest Moment When Everyone Become Friends ArrayUnion-FindSorting | Medium | 91% | 66.1% | ||
| #1102 | Path With Maximum Minimum Value ArrayBinary SearchDepth-First SearchBreadth-First SearchUnion-FindHeap (Priority Queue)MatrixDijkstra's Algorithm | Medium | 68% | 54.7% | ||
| #1632 | Rank Transform of a Matrix ArrayUnion-FindGraph TheoryTopological SortSortingMatrix | Hard | 56% | 42.4% | ||
| #1361 | Validate Binary Tree Nodes TreeDepth-First SearchBreadth-First SearchUnion-FindGraph TheoryBinary Tree | Medium | 25% | 44.2% | ||
| #549 | Binary Tree Longest Consecutive Sequence II TreeDepth-First SearchBinary TreeDP on Trees | Medium | 25% | 50.1% | ||
| #2421 | Number of Good Paths ArrayHash TableTreeUnion-FindGraph TheorySorting | Hard | 25% | 56.5% | ||
| #1697 | Checking Existence of Edge Length Limited Paths ArrayTwo PointersUnion-FindGraph TheorySorting | Hard | 25% | 63.4% | ||
| #3600 | Maximize Spanning Tree Stability with Upgrades Binary SearchGreedyUnion-FindGraph TheoryMinimum Spanning Tree | Hard | 13% | 66.2% | ||
| #2368 | Reachable Nodes With Restrictions ArrayHash TableTreeDepth-First SearchBreadth-First SearchUnion-FindGraph Theory | Medium | 100% | 60.6% | ||
| #928 | Minimize Malware Spread II ArrayHash TableDepth-First SearchBreadth-First SearchUnion-FindGraph Theory | Hard | 100% | 45.8% | ||
| #3710 | Maximum Partition Factor ArrayBinary SearchDepth-First SearchBreadth-First SearchUnion-FindGraph Theory | Hard | 93% | 32.1% | ||
| #3619 | Count Islands With Total Value Divisible by K ArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix | Medium | 79% | 56.2% | ||
| #1724 | Checking Existence of Edge Length Limited Paths II Depth-First SearchUnion-FindGraph TheoryDesignSortingHeap (Priority Queue)Minimum Spanning Tree | Hard | 75% | 51.6% | ||
| #3608 | Minimum Time for K Connected Components Binary SearchUnion-FindGraph TheorySorting | Medium | 54% | 45.7% | ||
| #2307 | Check for Contradictions in Equations ArrayStringDepth-First SearchUnion-FindGraph Theory | Hard | 50% | 44.0% | ||
| #711 | Number of Distinct Islands II ArrayHash TableDepth-First SearchBreadth-First SearchUnion-FindSortingMatrixHash Function | Hard | 25% | 55.5% | ||
| #1168 | Optimize Water Distribution in a Village Union-FindGraph TheoryHeap (Priority Queue)Minimum Spanning TreePrim's AlgorithmKruskal's AlgorithmBorůvka's Algorithm | Hard | 25% | 65.6% | ||
| #952 | Largest Component Size by Common Factor ArrayHash TableMathUnion-FindNumber TheoryPrime Factorization | Hard | 25% | 43.4% | ||
| #2076 | Process Restricted Friend Requests Union-FindGraph Theory | Hard | 25% | 61.0% | ||
| #352 | Data Stream as Disjoint Intervals Hash TableBinary SearchUnion-FindDesignData StreamOrdered Set | Hard | 13% | 60.3% | ||
| #3235 | Check if the Rectangle Corner Is Reachable ArrayMathDepth-First SearchBreadth-First SearchUnion-FindGeometry | Hard | 13% | 25.2% | ||
| #2612 | Minimum Reverse Operations ArrayHash TableBreadth-First SearchUnion-FindOrdered Set | Hard | 75% | 17.2% | ||
| #1627 | Graph Connectivity With Threshold ArrayMathUnion-FindNumber Theory | Hard | 28% | 49.7% | ||
| #1998 | GCD Sort of an Array ArrayMathUnion-FindSortingNumber TheoryPrime FactorizationEuclidean AlgorithmGreatest Common Divisor | Hard | 27% | 50.4% | ||
| #1135 | Connecting Cities With Minimum Cost Union-FindGraph TheoryHeap (Priority Queue)Minimum Spanning Tree | Medium | 25% | 63.6% | ||
| #2782 | Number of Unique Categories Union-FindInteractiveCounting | Medium | 25% | 84.0% | ||
| #685 | Redundant Connection II Depth-First SearchBreadth-First SearchUnion-FindGraph Theory | Hard | 25% | 36.4% | ||
| #2424 | Longest Uploaded Prefix Hash TableBinary SearchUnion-FindDesignBinary Indexed TreeSegment TreeHeap (Priority Queue)Ordered Set | Medium | 25% | 55.2% | ||
| #2371 | Minimize Maximum Value in a Grid ArrayUnion-FindGraph TheoryTopological SortSortingMatrix | Hard | 25% | 70.1% | ||
| #3695 | Maximize Alternating Sum Using Swaps ArrayGreedyUnion-FindSorting | Hard | 18% | 64.8% | ||
| #3493 | Properties Graph ArrayHash TableDepth-First SearchBreadth-First SearchUnion-FindGraph Theory | Medium | 13% | 49.1% | ||
| #2573 | Find the String with LCP ArrayStringDynamic ProgrammingGreedyUnion-FindMatrix | Hard | 13% | 63.1% |
Showing 83 of 83 problems in Union-Find (Disjoint Set)Filtered: All Companies