Skip to content
Commitwise
Menu
Coding Interview

Union-Find

Track which items belong together as connections arrive, with find and union in nearly constant time thanks to path compression and union by size, and use it for connected components, cycle detection, merging accounts and Kruskal's minimum spanning tree, in Swift, Kotlin, Java and TypeScript.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A social network adds friendships one at a time and needs to answer “are these two people in the same circle of friends?” instantly. A network team adds cables between servers and wants to know when a new cable creates a loop. An account system discovers that two sign-ups share an email and must merge them. Re-running a graph search after every new connection works, but costs O(V + E) each time.

Union-FindUnion-FindA structure that tracks which elements are in the same group, with fast find (which group?) and union (merge two groups).Open in glossary → (also called a disjoint set union, DSU) keeps track of groups as connections arrive. It answers two questions, “which group is this in?” (find) and “merge these two groups” (union), each in nearly constant time. It’s about twenty lines of code and shows up constantly in interviews and in real systems.

New to some of these? Open what you need, or skip ahead.

Basics:What is a graph?

A graph is a set of nodes (people, servers, cities) connected by edges (friendships, cables, roads). Nodes that can reach each other through edges form a connected component. The Graphs tutorial covers searching them with BFS and DFS.

Basics:What does O(n) mean?

Big-O describes how the amount of work grows with the size of the input n:

  • O(1): the same work whatever the size (reading array[5]).
  • O(log n): grows very slowly (about 20 steps for a million items).
  • O(n): grows in step with the input (one pass over the array).
  • O(n²): comparing every item with every other item, which gets slow fast.

You’ll see it next to every solution, for time and for extra space (memory). The Big-O tutorial explains it properly.

Part Not started

Groups that merge

Imagine every person in a company has a “my boss is…” note. To find out which department someone is in, you follow the notes up until you reach someone whose note says “myself”: the head of the department. That person represents the whole group.

Union-Find works exactly like that:

  • parent is an array: parent[i] is the element i points to. At the start, everyone points to themselves: every element is its own group.
  • find(x) follows parents from x up to the root (an element that points to itself). Two elements are in the same group if they have the same root.
  • union(a, b) finds both roots and makes one of them point to the other. Now both groups have one root, so they’re one group.

Two small tricks keep the chains short, so find stays fast:

  • Union by size: attach the smaller group under the larger one, so trees stay shallow.
  • Path compression: after find(x) reaches the root, make every element on the way point directly at the root. The next find is one step.

The structure is a forest stored in a parent array; a root identifies its set. find follows parent links to the root; union links one root under the other. With union by size (or rank) alone, trees have height O(log n); with path compression alone, amortized cost is O(log n); with both, the amortized cost per operation is O(α(n)), the inverse Ackermann function, which is at most 4 for any input that fits in the universe. Iterative compression (two passes, or path halving parent[x] = parent[parent[x]]) avoids recursion depth issues. Union-Find handles incremental connectivity only: it can’t delete edges or split sets (that needs offline reverse processing or dynamic connectivity structures). Map non-integer items (emails, coordinates) to indices with a hash map, or use a map-based parent.

struct UnionFind {
    private var parent: [Int]
    private var size: [Int]
    private(set) var components: Int

    init(_ n: Int) {
        parent = Array(0..<n)                          // everyone starts as their own root
        size = Array(repeating: 1, count: n)
        components = n
    }

    mutating func find(_ x: Int) -> Int {
        var root = x
        while parent[root] != root { root = parent[root] }
        var node = x
        while parent[node] != root {                   // path compression
            let next = parent[node]
            parent[node] = root
            node = next
        }
        return root
    }

    @discardableResult
    mutating func union(_ a: Int, _ b: Int) -> Bool {
        var rootA = find(a), rootB = find(b)
        if rootA == rootB { return false }             // already in the same group
        if size[rootA] < size[rootB] { swap(&rootA, &rootB) }
        parent[rootB] = rootA                          // smaller tree under the larger
        size[rootA] += size[rootB]
        components -= 1
        return true
    }
}
class UnionFind(n: Int) {
    private val parent = IntArray(n) { it }            // everyone starts as their own root
    private val size = IntArray(n) { 1 }
    var components = n
        private set

    fun find(x: Int): Int {
        var root = x
        while (parent[root] != root) root = parent[root]
        var node = x
        while (parent[node] != root) {                 // path compression
            val next = parent[node]
            parent[node] = root
            node = next
        }
        return root
    }

    fun union(a: Int, b: Int): Boolean {
        var rootA = find(a)
        var rootB = find(b)
        if (rootA == rootB) return false               // already in the same group
        if (size[rootA] < size[rootB]) rootA = rootB.also { rootB = rootA }
        parent[rootB] = rootA                          // smaller tree under the larger
        size[rootA] += size[rootB]
        components--
        return true
    }
}
class UnionFind {
    private final int[] parent;
    private final int[] size;
    private int components;

    UnionFind(int n) {
        parent = new int[n];
        size = new int[n];
        for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; }   // everyone starts as their own root
        components = n;
    }

    int find(int x) {
        int root = x;
        while (parent[root] != root) root = parent[root];
        while (parent[x] != root) {                    // path compression
            int next = parent[x];
            parent[x] = root;
            x = next;
        }
        return root;
    }

    boolean union(int a, int b) {
        int rootA = find(a), rootB = find(b);
        if (rootA == rootB) return false;              // already in the same group
        if (size[rootA] < size[rootB]) { int t = rootA; rootA = rootB; rootB = t; }
        parent[rootB] = rootA;                         // smaller tree under the larger
        size[rootA] += size[rootB];
        components--;
        return true;
    }

    int components() { return components; }
}
class UnionFind {
  private readonly parent: number[];
  private readonly size: number[];
  components: number;

  constructor(n: number) {
    this.parent = Array.from({ length: n }, (_, i) => i);   // everyone starts as their own root
    this.size = new Array(n).fill(1);
    this.components = n;
  }

  find(x: number): number {
    let root = x;
    while (this.parent[root] !== root) root = this.parent[root];
    while (this.parent[x] !== root) {                       // path compression
      const next = this.parent[x];
      this.parent[x] = root;
      x = next;
    }
    return root;
  }

  union(a: number, b: number): boolean {
    let rootA = this.find(a);
    let rootB = this.find(b);
    if (rootA === rootB) return false;                      // already in the same group
    if (this.size[rootA] < this.size[rootB]) [rootA, rootB] = [rootB, rootA];
    this.parent[rootB] = rootA;                             // smaller tree under the larger
    this.size[rootA] += this.size[rootB];
    this.components--;
    return true;
  }
}
  • find first walks up to the root, then walks the same path again and points every node straight at the root.
  • union works on the two roots. If they’re the same, the elements were already connected, and union returns false, which is very useful (next part).
  • components starts at n and drops by one on every successful union, so you always know how many groups there are.

Predict the output

A Union-Find over 5 elements (0 to 4) runs union(0, 1), union(2, 3), union(1, 3). How many components are there, and are 0 and 2 connected?

Spot the bugMerging that splits groups

Tap the line with the bug.

mutating func union(_ a: Int, _ b: Int) {
    parent[a] = b
    components -= 1
}
fun union(a: Int, b: Int) {
    parent[a] = b
    components--
}
void union(int a, int b) {
    parent[a] = b;
    components--;
}
union(a: number, b: number): void {
  this.parent[a] = b;
  this.components--;
}

Why both optimizations matter

Predict the output

A Union-Find without union by size and without path compression always links parent[rootA] = rootB. It runs union(0, 1), union(0, 2), union(0, 3), …, union(0, n − 1). How long does the last find(0) take?

Deep diveRecursion and stack depthInterview favorite

The textbook path compression is recursive: parent[x] = find(parent[x]). On a degenerate chain of 100,000 nodes (possible when union by size is missing, or before compression has happened), that’s 100,000 nested calls: a StackOverflowError on the JVM, a crash in Swift, RangeError: Maximum call stack size exceeded in JavaScript. The iterative two-pass version in this lesson, or path halving (parent[x] = parent[parent[x]] while walking), has the same complexity with constant stack use, which is what production code should use.

  • Forest in a parent array; root = set id. find to root; union links roots.
  • Union by size/rank → O(log n) height; path compression → flattening; both → O(α(n)) amortized (≤ 4 in practice).
  • Iterative compression or path halving: no deep recursion on degenerate chains.
  • union returning false = already connected: cycle detection for free. Track component count.
  • Incremental only: no edge deletion or set splitting. Map arbitrary keys to indices.

Check this part

  1. How do you know two elements are in the same group?

  2. What does union by size do?

  3. What is the amortized cost per operation with both optimizations?

  4. Which operation can Union-Find not support efficiently?

Each element points to a parent; following parents leads to the group's root, which identifies the group. find returns the root; union links one root under the other. Path compression (point nodes straight at the root while finding) and union by size (attach the smaller tree under the larger) make both nearly O(1), formally O(α(n)). Always link roots, never the elements themselves.

Part Not started

Components, cycles and merges

Union-Find turns several graph problems into one loop over the edges. The most direct one is Redundant Connection: a graph started as a tree with n nodes (labelled 1 to n), and one extra edge was added. Return the edge that can be removed so the graph becomes a tree again (if several, the one that appears last in the input).

edges = [[1,2], [1,3], [2,3]]                → [2,3]
edges = [[1,2], [2,3], [3,4], [1,4], [1,5]]  → [1,4]

Go through the edges in order and union their endpoints. While the graph is still a forest, every edge connects two different groups. The first edge whose endpoints are already in the same group closes a loop: that’s the redundant one. union already tells you this, because it returns false when the roots are equal.

An undirected edge (u, v) creates a cycle exactly when u and v are already connected; processing edges in input order, the first such edge is also the last one that could be removed in input order (the problem guarantees a single extra edge). O(E · α(V)) time, O(V) space. The same “union returns false” check is the cycle test inside Kruskal’s algorithm.

func findRedundantConnection(_ edges: [[Int]]) -> [Int] {
    var uf = UnionFind(edges.count + 1)            // nodes are labelled 1...n
    for edge in edges {
        if !uf.union(edge[0], edge[1]) { return edge }   // already connected: this edge closes a cycle
    }
    return []
}
fun findRedundantConnection(edges: Array<IntArray>): IntArray {
    val uf = UnionFind(edges.size + 1)             // nodes are labelled 1..n
    for (edge in edges) {
        if (!uf.union(edge[0], edge[1])) return edge   // already connected: this edge closes a cycle
    }
    return IntArray(0)
}
int[] findRedundantConnection(int[][] edges) {
    UnionFind uf = new UnionFind(edges.length + 1);    // nodes are labelled 1..n
    for (int[] edge : edges) {
        if (!uf.union(edge[0], edge[1])) return edge;  // already connected: this edge closes a cycle
    }
    return new int[0];
}
function findRedundantConnection(edges: number[][]): number[] {
  const uf = new UnionFind(edges.length + 1);          // nodes are labelled 1..n
  for (const [a, b] of edges) {
    if (!uf.union(a, b)) return [a, b];                // already connected: this edge closes a cycle
  }
  return [];
}

A tree with n nodes has n − 1 edges, and one extra was added, so there are n edges in total: edges.count + 1 slots fit labels 1 to n.

Exercisemedium

Number of Provinces

There are n cities. isConnected[i][j] = 1 means cities i and j are directly connected. A province is a group of cities connected directly or through other cities. Return the number of provinces.

isConnected = [[1,1,0],
               [1,1,0],
               [0,0,1]]   → 2
›

Each province is a connected component. Start with n groups and union every pair that’s connected.

›

The matrix is symmetric, so you only need the pairs with j > i.

SolutionTry it yourself firstTime O(n² · α(n))Space O(n)
func findCircleNum(_ isConnected: [[Int]]) -> Int {
    let n = isConnected.count
    var uf = UnionFind(n)
    for i in 0..<n {
        for j in (i + 1)..<n where isConnected[i][j] == 1 {
            uf.union(i, j)
        }
    }
    return uf.components
}
fun findCircleNum(isConnected: Array<IntArray>): Int {
    val n = isConnected.size
    val uf = UnionFind(n)
    for (i in 0 until n) {
        for (j in i + 1 until n) {
            if (isConnected[i][j] == 1) uf.union(i, j)
        }
    }
    return uf.components
}
int findCircleNum(int[][] isConnected) {
    int n = isConnected.length;
    UnionFind uf = new UnionFind(n);
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (isConnected[i][j] == 1) uf.union(i, j);
        }
    }
    return uf.components();
}
function findCircleNum(isConnected: number[][]): number {
  const n = isConnected.length;
  const uf = new UnionFind(n);
  for (let i = 0; i < n; i++) {
    for (let j = i + 1; j < n; j++) {
      if (isConnected[i][j] === 1) uf.union(i, j);
    }
  }
  return uf.components;
}

Swift note

In Swift, (i + 1)..<n is empty when i + 1 == n, which is fine. A closed range (i + 1)...(n - 1) would crash for the last i, because its lower bound would be greater than its upper bound.

A DFS or BFS from every unvisited city also works in O(n²). Union-Find shines when the connections arrive one by one and you need the count after each.

More patterns

  • Kruskal’s minimum spanning tree: sort edges by weight, add each edge whose union succeeds, stop after V − 1 edges. O(E log E), dominated by sorting.
  • Grids: index cells as row * cols + col; Number of Islands II (land added cell by cell, report the island count after each) is the canonical online version.
  • Equations and equivalences: “a == b” constraints first, then check “a != b” against them (Satisfiability of Equality Equations); weighted Union-Find stores a ratio to the parent for “a / b = 2” problems.

Production puzzles

Exercisemedium

Accounts Merge

Each account is [name, email1, email2, …]. Two accounts belong to the same person if they share at least one email (names can repeat for different people). Merge them and return each person’s name with their emails sorted.

[["John","john@mail.com","john_work@mail.com"],
 ["John","john@mail.com","john_home@mail.com"],
 ["Mary","mary@mail.com"]]
→ [["John","john@mail.com","john_home@mail.com","john_work@mail.com"], ["Mary","mary@mail.com"]]
›

Union account indices, not emails: remember, for each email, the first account that had it, and union every later account with that one.

SolutionTry it yourself firstTime O(E log E) for sorting, E = total emailsSpace O(E)
fun accountsMerge(accounts: List<List<String>>): List<List<String>> {
    val uf = UnionFind(accounts.size)
    val owner = HashMap<String, Int>()                     // email → first account index that had it
    accounts.forEachIndexed { i, account ->
        for (email in account.drop(1)) {
            val first = owner.putIfAbsent(email, i)
            if (first != null) uf.union(first, i)
        }
    }
    val emailsByRoot = HashMap<Int, java.util.TreeSet<String>>()
    owner.forEach { (email, i) -> emailsByRoot.getOrPut(uf.find(i)) { java.util.TreeSet() }.add(email) }
    return emailsByRoot.map { (root, emails) -> listOf(accounts[root][0]) + emails }
}

Unioning account indices keeps the structure as small as the number of accounts. A common mistake is to group by name: two different Johns would be merged. Another is to union emails within an account but forget to connect accounts through shared emails; the owner map does that.

  • Components: union every edge, read the count; works online as edges arrive.
  • Undirected cycle: the first edge whose union returns false (Redundant Connection, Kruskal’s check).
  • Kruskal: sort edges, keep successful unions, stop at V − 1 edges: O(E log E).
  • Map keys to indices (emails → first owning account; grid cell → r * cols + c); weighted Union-Find for ratio constraints.
  • Prefer BFS/DFS for one-off static connectivity; Union-Find for incremental queries.

Check this part

  1. Processing edges one by one, how do you spot the edge that creates a cycle?

  2. How do you count connected components with Union-Find?

  3. In Kruskal's algorithm, what decides whether an edge is added?

  4. Why union account indices instead of names in Accounts Merge?

Count connected components by unioning every edge and reading the component count. Detect the edge that closes a cycle in an undirected graph: it's the first union that returns false. Merge records that share keys (Accounts Merge) by mapping keys to indices. Kruskal's minimum spanning tree sorts edges by weight and keeps those whose union succeeds.

Key takeaways

  • Union-Find tracks groups: find returns a group’s root, union merges two groups.
  • Always link roots, never the elements themselves.
  • Union by size and path compression keep it nearly O(1).
  • When union says the elements were already connected, a new edge closes a cycle.
  • Both optimizations together give O(α(n)) amortized; use iterative compression.
  • It’s the tool for incremental connectivity: components after each edge, cycle checks, Kruskal.
  • Map arbitrary keys to indices; consider weighted variants for relational constraints.
  • It can’t delete edges; choose BFS/DFS for static one-off questions.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.