Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Graphs

Union-Find (Disjoint Set)

~O(α(n))

Each set has a representative; union merges two roots, find returns a root. Path compression + union by rank keep it near-constant.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
UnlocksMinimum Spanning TreeOffline Query ProcessingKruskal Reconstruction TreeParallel Binary Search
0%
mastery
0/28 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Connectivity with only additions: count components, group equivalents (accounts, equations), redundant edge in an undirected graph, Kruskal.

  1. 1Brute force

    Re-run BFS after each merge: O(q (V+E)).

  2. 2The observation

    Re-traversal: each set is a tree whose root is its id.

  3. 3Why it works

    find(x) == find(y) iff x and y were connected by earlier unions.

Reach for it when

  • +Connectivity / number of connected components, grouping, or merging sets that only ever combine.
  • +Detecting a cycle / redundant edge in an undirected graph as you add edges.
  • +Online queries interleaved with unions (Accounts Merge, friend circles, Kruskal's MST).

Not when

  • ×You need the actual path or distancesuse BFS/DFS or Dijkstra
  • ×Groups can split (edge deletions)use Reverse offline, or DSU with rollback
  • ×Directed reachability, ordering, or directed cyclesuse Topological sort / directed DFS

Intuition

Union-Find (Disjoint Set Union) answers one question blazing fast: "are these two things in the same group?" — and lets you merge groups on the fly. Think of friend circles: each person points to a "representative" friend; to check if two people are in the same circle, follow each one's chain of pointers up to the top representative and see if it's the same person.

Read the full intuition

Two operations:

  • find(x) — follow parent pointers up to the root (the group's representative).
  • union(a, b) — find both roots; point one root at the other, merging the two trees.

Naively the chains get long. Two tiny optimizations make it almost O(1) per op:

  • Path compression: during find, re-point every node you pass straight to the root, flattening the tree.
  • Union by rank/size: always attach the smaller tree under the bigger one, so trees stay shallow.

Together they give near-constant O(α(n)) (inverse Ackermann — effectively ≤ 4 for any real input).

Worked: nodes 0–4, edges (0-1),(1-2),(3-4). Start parent=[0,1,2,3,4] (everyone their own group, 5 groups). union(0,1)→4 groups. union(1,2): root of 1 is 0, root of 2 is 2 → merge → 3 groups. union(3,4)→2 groups. Now find(0)==find(2) (connected), find(0)!=find(3). Number of components = 2.

Key idea

Reach for Union-Find when the problem is "how many groups / are these connected / is adding this edge redundant" and groups only ever merge (never split). If you also need shortest paths or order, use BFS/DFS or topo-sort instead.

Why it costs what it costs

Time O(E·α(n)). each find/union is near-constant α(n) (≤4 in practice) after path compression + union by rank; E operations total.

Space O(n). parent and rank arrays of size n.

Practice

Next · Foundation

Number of Provinces

Union every edge; count roots.

0/28 solved
  • Number of ProvincesFoundationFoundationAmazon, UberMedium
  • Number of Connected Components in an Undirected GraphApply it · Edge list input.Apply itPremiumMedium
  • Redundant ConnectionOne change · Find the edge closing a cycle.One changeAmazon, MetaMedium
  • Graph Valid TreeOne change · Tree check.One changePremiumMedium
  • Satisfiability of Equality EquationsTwists · Constraints of two kinds.TwistsGoogle, CitadelMedium
  • Accounts MergeBranches · Union by a shared key (email).BranchesMeta, AmazonMedium
  • Most Stones Removed with Same Row or ColumnBranches · Union rows with columns.BranchesGoogle, CitadelMedium
  • Evaluate DivisionBranches · Edges carry ratios.BranchesGoogle, UberMedium
  • Smallest String With SwapsCombine · Components then per-component sorting.CombineGoogle, UberMedium
  • Checking Existence of Edge Length Limited PathsMastery checkMastery checkHard
  • Min Cost to Connect All PointsGoogle, UberMedium
  • Connecting Cities With Minimum CostPremiumMedium

Pitfalls

Classic bugs

  • !No path compression and no union by rank/size → find degrades to O(n). Compression alone is fast but not the textbook bound.
  • !parent[a] = parent[b] instead of linking roots find(a), find(b) — corrupts the structure.
  • !Have union return whether it merged; False means the edge is redundant (cycle).
  • !Non-integer ids (emails, coordinates): map to indices or use a dict-based parent.
  • !Components: start count = n, decrement on each successful union — don't rescan.

Looks like it, isn't

  • Is Graph Bipartite? needs Bipartite Check / 2-Colouring
    Why
    DSU with parity works, but BFS 2-colouring is the direct test.
Go deepervariants and techniques · 5 combinations · resources

Variants and techniques

  • DSU with Rollback / Offline Dynamic ConnectivityCP 2400+Union by size with no path compression, so each union can be undone from a stack. Put each edge's lifetime on a segment tree over time and DFS that tree, uniting on entry and rolling back on exit. This answers connectivity under insertions and deletions offline in O(q log q log n).
  • Count componentsInit count=n, decrement on each merge. Number of Provinces / Connected Components.
  • Cycle / redundant edgeIf union(u,v) finds them already joined, that edge forms a cycle. Redundant Connection, Graph Valid Tree.
  • Merge by attributeMap strings/emails to ids, union accounts sharing an email, group by root. Accounts Merge.
  • Kruskal's MSTSort edges, union endpoints if not already connected, summing accepted weights. Min Cost to Connect All Points.

Combinations

  • Offline Query Processing+Union-Find (Disjoint Set)

    queries 'connected using edges with weight < limit'; reverse deletions

    Offline Query Processing:
    sorts edges and queries by threshold
    Union-Find (Disjoint Set):
    adds edges incrementally

    Checking Existence of Edge Length Limited PathsNetwork Breakdown

  • Minimum Spanning Tree+Union-Find (Disjoint Set)+Greedy

    connect all nodes at minimum cost

    Minimum Spanning Tree:
    the goal (spanning tree)
    Union-Find (Disjoint Set):
    cycle check per edge
    Greedy:
    process edges by increasing weight (cut property)

    Connecting Cities With Minimum CostRoad ReparationMin Cost to Connect All Points

  • DSU with Rollback / Offline Dynamic Connectivity+Segment Tree / Fenwick (BIT)+Offline Query Processing

    add edge / remove edge / count components (or check bipartiteness) with all operations given upfront

    DSU with Rollback / Offline Dynamic Connectivity:
    unite on entry, roll back on exit
    Segment Tree / Fenwick (BIT):
    a segment tree over time storing each edge in the O(log q) nodes covering its lifetime
    Offline Query Processing:
    every add/remove/query must be known before processing

    Dynamic ConnectivityExtending Set of PointsBipartite Checking

  • Parallel Binary Search+Union-Find (Disjoint Set)

    for each pair, the first time it becomes connected as edges are added

    Parallel Binary Search:
    every query binary searches the day on which its pair connects
    Union-Find (Disjoint Set):
    replay the edge additions once per round

    New Roads Queries

  • Union-Find (Disjoint Set)+Bitset Optimisation+0/1 Knapsack

    split the vertices into two groups without breaking components, for every possible size

    Union-Find (Disjoint Set):
    component sizes
    Bitset Optimisation:
    makes the subset sum fast
    0/1 Knapsack:
    which totals of component sizes are achievable

    School Excursion

Resources

  • Graph Theory playlistWilliam Fiset · video
  • Graph TraversalUSACO Guide · course
  • Disjoint Set Unioncp-algorithms · article
  • Dijkstracp-algorithms · article
  • Topological sortingcp-algorithms · article
  • Shortest paths visualizerVisuAlgo · tool
  • Graph cheatsheetTech Interview Handbook · article
Topological SortDijkstra (Weighted Shortest Path)
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial