Union-Find (Disjoint Set)

Data Structures

Connectivity, cycle detection, and clustering in undirected networks

89 problems·1 Easy·50 Medium·38 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. 1.Initialize `parent = list(range(n))` and `rank = [1] * n`.
  2. 2.Implement `find(x)`: recursively find root while flattening tree (`parent[x] = find(parent[x])`).
  3. 3.Implement `union(x, y)`: find roots `rx = find(x)`, `ry = find(y)`. If equal, they already connect (cycle detected!).
  4. 4.If unequal, attach smaller rank root under larger rank root, and decrement component count.
  5. 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
Medium·93 companies·Max freq 100%·Acc 64.7%
RedfinAMDAnduril+90
Medium·49 companies·Max freq 100%·Acc 47.2%
Wissen TechnologyWissen TechnologyNeetCode 150+46
Medium·25 companies·Max freq 100%·Acc 64.4%
Tower Research CapitalTower Research CapitalUrban Company+22
Medium·22 companies·Max freq 100%·Acc 74.1%
GrubhubSchlumbergerRoku+19
Hard·18 companies·Max freq 90%·Acc 56.9%
SnapSnapMoloco+15
Medium·18 companies·Max freq 83%·Acc 61.7%
GrabDocusignByteDance+15
Medium·15 companies·Max freq 87%·Acc 45.8%
PornhubMolocoNeetCode 150+12
Hard·14 companies·Max freq 100%·Acc 0.4%
DropboxNCRBNY Mellon+11
Medium·13 companies·Max freq 100%·Acc 71.3%
DirectiNeetCode 150NeetCode 150+10
Medium·13 companies·Max freq 92%·Acc 62.9%
SnapTikTokSnap+10
Medium·13 companies·Max freq 77%·Acc 52.8%
SamsungMeeshoTikTok+10
Medium·12 companies·Max freq 100%·Acc 50.1%
ZenefitsNeetCode 150Blind 75+9
Medium·11 companies·Max freq 100%·Acc 0.7%
Akuna CapitalPhonePeIBM+8
Medium·11 companies·Max freq 100%·Acc 65.1%
General MotorsXX+8
Medium·11 companies·Max freq 88%·Acc 59.6%
LimeSamsungAmazon+8
Hard·11 companies·Max freq 78%·Acc 68.0%
WeRideNeetCode 150NeetCode 150+8
Medium·11 companies·Max freq 77%·Acc 67.9%
BoxNeetCode 150NeetCode 150+8
Medium·10 companies·Max freq 100%·Acc 60.8%
PhonePePayPalPalantir+7
Hard·10 companies·Max freq 93%·Acc 40.7%
UberMolocoAurora+7
Medium·10 companies·Max freq 75%·Acc 0.7%
PhonePeAtlassianIBM+7
Medium·9 companies·Max freq 100%·Acc 70.7%
Two SigmaBloombergAmazon+6
Medium·9 companies·Max freq 67%·Acc 63.6%
WaymoNutanixVisa+6
Hard·8 companies·Max freq 66%·Acc 0.6%
Squarepoint CapitalConfluentCitadel+5
Medium·8 companies·Max freq 62%·Acc 0.6%
ZomatoIntuitUber+5
Medium·7 companies·Max freq 100%·Acc 52.0%
Sumo LogicSumo LogicCleverTap+4
Medium·7 companies·Max freq 75%·Acc 56.1%
CiscoSalesforceZeta Global+4
Medium·6 companies·Max freq 100%·Acc 63.4%
NutanixWeRideAmazon+3
Medium·6 companies·Max freq 100%·Acc 73.0%
XXZepto+3
Hard·6 companies·Max freq 75%·Acc 68.2%
DE ShawTuringGoogle+3
Hard·6 companies·Max freq 75%·Acc 59.2%
JPMorgan ChaseUberAmazon+3
Hard·6 companies·Max freq 63%·Acc 66.9%
UberAccentureGoogle+3
Medium·6 companies·Max freq 52%·Acc 77.6%
UberTikTokGoogle+3
Hard·6 companies·Max freq 50%·Acc 0.7%
UberDE ShawAmazon+3
Medium·6 companies·Max freq 27%·Acc 72.0%
GoogleBloombergMicrosoft+3
Medium·6 companies·Max freq 25%·Acc 73.5%
AmazonGoogleMicrosoft+3
Medium·5 companies·Max freq 100%·Acc 66.2%
UnbxdBloombergGoogle+2
Medium·5 companies·Max freq 68%·Acc 81.1%
ClouderaAmazonGoogle+2
Medium·5 companies·Max freq 63%·Acc 50.1%
SnapSnapAmazon+2
Easy·5 companies·Max freq 38%·Acc 55.5%
BloombergMicrosoftAmazon+2
Medium·5 companies·Max freq 38%·Acc 70.7%
GoogleBloombergAmazon+2
Hard·5 companies·Max freq 38%·Acc 56.4%
DoorDashGoogleApple+2
Medium·5 companies·Max freq 38%·Acc 67.2%
GoogleOracleMeta+2
Medium·4 companies·Max freq 100%·Acc 0.6%
CruiseCruiseMoveworks+1
Hard·4 companies·Max freq 88%·Acc 0.4%
SnapSnapPhonePe+1
Medium·4 companies·Max freq 79%·Acc 0.7%
Sumo LogicSumo LogicGoogle+1
Medium·4 companies·Max freq 63%·Acc 43.7%
SalesforceAppleGoogle+1
Medium·4 companies·Max freq 50%·Acc 51.4%
RipplingGoogleApple+1
Medium·4 companies·Max freq 50%·Acc 54.8%
TikTokGoogleAmazon+1
Hard·4 companies·Max freq 42%·Acc 68.7%
AtlassianGoogleAmazon+1
Hard·4 companies·Max freq 38%·Acc 45.1%
InfosysAmazonGoogle+1
50 displayed (of 50 matching)Filtered: All Companies

Top Companies Testing Union-Find (Disjoint Set)

Browse company-specific interview problem lists and recency breakdowns:

Explore All 22 DSA Coding Patterns

Master core algorithmic patterns tested in FAANG & Big Tech coding interviews.

Patterns Hub

Union-Find (Disjoint Set) frequently asked questions

What is the Union-Find (Disjoint Set) pattern in coding interviews?

Connectivity, cycle detection, and clustering in undirected networks It is categorized under Data Structures and features 89 curated interview problems across Easy (1), Medium (50), and Hard (38) difficulties.

Which tech companies frequently test Union-Find (Disjoint Set)?

Companies frequently asking Union-Find (Disjoint Set) questions include Google, Amazon, Meta, Microsoft, Uber, Bloomberg.

How do I master the Union-Find (Disjoint Set) pattern?

Start by studying the algorithmic strategy and template code, then practice Easy and Medium problems before attempting Hard problems under timed conditions.