Skip to content
We areTOP 1%
DSA · Pro · Pattern 3 of 9

Union-Find (DSU)

12 problems.
Your progress0%
1st Visit
0/12
2nd Visit
0/12
Revise
0/12

About this pattern

A disjoint set union (DSU) maintains a partition of elements into groups and supports two operations: find, which returns the representative of an element's group, and unite, which merges two groups. With path compression and union by size, both run in near-constant amortised time. Reach for it when a problem repeatedly merges items that are connected, equivalent or share an attribute, and then asks whether two items belong together, how many groups remain, or how large a group is. It detects cycles while undirected edges are added and underpins Kruskal's algorithm. Processing queries offline in sorted order often turns a hard problem into a sequence of merges.

struct DSU {
    vector<int> parent, sz;
    DSU(int n) : parent(n), sz(n, 1) { iota(parent.begin(), parent.end(), 0); }
    int find(int x) {
        while (x != parent[x]) x = parent[x] = parent[parent[x]];  // path halving
        return x;
    }
    bool unite(int a, int b) {
        a = find(a); b = find(b);
        if (a == b) return false;                                  // already joined
        if (sz[a] < sz[b]) swap(a, b);
        parent[b] = a; sz[a] += sz[b];
        return true;
    }
};

Problems

Union-Find (DSU) questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Redundant ConnectionLeetCodeMedium Solve Redundant Connection on LeetCode (opens in a new tab)
2Satisfiability of Equality EquationsLeetCodeMedium Solve Satisfiability of Equality Equations on LeetCode (opens in a new tab)
3Number of Operations to Make Network ConnectedLeetCodeMedium Solve Number of Operations to Make Network Connected on LeetCode (opens in a new tab)
4News DistributionCodeforcesMedium 1400Solve News Distribution on Codeforces (opens in a new tab)
5Accounts MergeLeetCodeMedium Solve Accounts Merge on LeetCode (opens in a new tab)
6Most Stones Removed with Same Row or ColumnLeetCodeMedium Solve Most Stones Removed with Same Row or Column on LeetCode (opens in a new tab)
7Bear and Friendship ConditionCodeforcesMedium 1500Solve Bear and Friendship Condition on Codeforces (opens in a new tab)
8SocksCodeforcesMedium 1600Solve Socks on Codeforces (opens in a new tab)
9Destroying ArrayCodeforcesMedium 1600Solve Destroying Array on Codeforces (opens in a new tab)
10Path QueriesCodeforcesHard 1800Solve Path Queries on Codeforces (opens in a new tab)
11Making A Large IslandLeetCodeHard Solve Making A Large Island on LeetCode (opens in a new tab)
12Remove Max Number of Edges to Keep Graph Fully TraversableLeetCodeHard Solve Remove Max Number of Edges to Keep Graph Fully Traversable on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account