learngraphtheory.org

Guest

Sign in to keep your graphs and progress.

Cover of the book Graph Theory Through Problems

Practice book

Graph Theory Through Problems

300 Exercises with Hints, Worked Algorithms and Complete Solutions

By Mohammed Islam Hadjoudj

Learn graph theory by solving problems: 300 exercises, from routine checks to challenging proofs, each with a complete solution.

Available inKindlePaperback

13 chapters

Also by the authorGraph Algorithms for Coding Interviews100 solved interview problems with visual explanations and Python solutions.View on Amazon
Algorithm Selection

Select an algorithm and generate steps to begin visualization

Union-Find Visualizer

Which set is it in? Almost instantly

Each edge is a union of the sets of its two vertices: find follows parent pointers to the root, with union by rank and path compression

Time: O(m α(n))
Space: O(n)
Use Case: Kruskal's algorithm, connected components, image segmentation
Showing the example graph for this algorithm.
Optimizations

Each edge is one union, in the order the edges were drawn. Switch an option off to see the trees grow taller.

Algorithm Execution

Select an algorithm and generate steps to begin visualization

About Union-Find (Disjoint Set Union)

Union-find, also called disjoint set union (DSU), keeps a collection of disjoint sets and supports two operations: find, which tells which set an element is in, and union, which merges two sets. Every set is stored as a tree whose root represents it, and every element keeps a pointer to its parent. Bernard Galler and Michael Fischer introduced the structure in 1964, and Robert Tarjan proved in 1975 that with two simple optimizations it takes almost constant time per operation.

How it works

find(v) follows parent pointers from v up to the root of its tree. union(a, b) finds both roots and, if they differ, makes one the parent of the other. Union by rank puts the root of the shallower tree under the other, so no tree grows taller than log2(n). Path compression makes every vertex a find passes point straight at the root, which flattens the tree for later finds. With both, m operations on n elements cost O(m α(n)), where the inverse Ackermann function α(n) is at most 4 for any input that fits in a computer. In the visualizer each edge is one union, in the order the edges were drawn, parent pointers are drawn as arrows, and either optimization can be switched off to watch the trees grow tall.

Applications

Union-find is the heart of Kruskal's minimum spanning tree algorithm, where it rejects the edges that would close a cycle. It tracks connected components while edges arrive, groups pixels in image segmentation, merges equivalent types in compilers and duplicate accounts in identity resolution, and models percolation and maze generation. It is also one of the most frequent data structures in coding interviews and competitive programming.

Pseudocode

Both operations take a few lines, and each optimization changes one of them: union by rank decides which root goes under which, and path compression rewrites the parent pointers on the way back from a find.

MakeSet(v):
    parent[v] = v
    rank[v] = 0

Find(v):
    if parent[v] != v:
        parent[v] = Find(parent[v])        // path compression
    return parent[v]

Union(a, b):
    ra = Find(a)
    rb = Find(b)
    if ra == rb: return                    // already one set
    if rank[ra] < rank[rb]: swap(ra, rb)   // union by rank
    parent[rb] = ra
    if rank[ra] == rank[rb]: rank[ra] = rank[ra] + 1

The rank is an upper bound on the height of a root's tree. It grows only when two trees of equal rank are joined, and a tree of rank r has at least 2^r vertices, so no rank exceeds log2(n). Path compression can make the real height smaller than the rank, which is why the bound is called rank and not height.

Worked example, step by step

Run the ten unions this page loads on the vertices A to H, first with both optimizations and then without them, to see what they buy.

Example graph: Edges, in order: B-A, C-B, D-C, E-D, F-E, G-H, A-G, A-F, H-F, B-E.

  1. The first five unions. With union by rank, B-A makes B a root of rank 1, and C, D, E and F each go directly under B because their rank 0 is lower. B's tree has height 1.
  2. Two trees of equal rank. G-H makes G a root of rank 1. A-G finds the roots B and G, both of rank 1, so G goes under B and B's rank becomes 2.
  3. Unions inside one set. A-F, H-F and B-E find the same root B at both ends, so nothing changes. In Kruskal's algorithm these edges would close a cycle.
  4. Path compression. H-F finds H through H, G, B. Path compression then points H straight at B, so the next find from H takes one step.
  5. Without the optimizations. With both off, B-A, C-B, D-C, E-D and F-E build the chain A, B, C, D, E, F with F at the top. A-G then climbs five pointers from A, and so does A-F.

All eight vertices end in one set. The finds follow 10 parent pointers with the optimizations and 17 without them, and the gap grows quickly with the input: a chain of n vertices costs n steps per find, a tree of rank log2(n) only log2(n).

Complexity, and where it comes from

Time: O(m α(n)) · Space: O(n)

Union by rank alone keeps every tree at most log2(n) tall, so each find and union costs O(log n). Path compression alone also gives O(log n) amortized per operation. Together, Tarjan proved in 1975 that m operations on n elements take O(m α(n)) time, where α is the inverse of the Ackermann function, and Fredman and Saks showed in 1989 that no structure can do better. α(n) is at most 4 for every n below 2^65536, so in practice each operation takes constant time. The structure stores one parent and one rank per element, O(n) space.

When to use Union-Find (Disjoint Set Union), and when not to

Union-find answers one question, whether two elements are connected, and only while sets merge. Other structures cover the other cases.

AlternativePrefer it whenCost
BFS or DFSThe graph is fixed and the components are needed once: one traversal labels every vertex.O(V + E)
Quick-find (an array of set labels)Finds must take O(1) and unions are rare: every union relabels a whole set.O(1) find, O(n) union
Dynamic connectivity structuresEdges are deleted as well as added. Union-find cannot split a set.polylogarithmic per update
Kruskal with union-findBuilding a minimum spanning tree: sort the edges, then add each edge whose ends have different roots.O(E log E)

Common pitfalls

  • Comparing parents instead of roots. Two elements are in the same set when their finds return the same root, not when their parents are equal. Checking parent[a] == parent[b] misses every pair at different depths.
  • Linking a vertex that is not a root. Union must link the roots, parent[find(b)] = find(a), not parent[b] = a. Linking a non-root cuts it from its old tree and silently splits a set.
  • Deep recursion in find. On a long chain, before any compression, a recursive find can overflow the call stack. An iterative two-pass find, or path halving, avoids that.
  • Expecting deletions. Union-find cannot undo a union or split a set. Problems with removals need another approach, such as processing the edges in reverse order, or a different structure.

Frequently asked questions

What is union-find?
A data structure that keeps elements in disjoint sets and supports find, which returns the representative of an element's set, and union, which merges two sets. It is also called disjoint set union (DSU).
What do union by rank and path compression do?
Union by rank hangs the shorter tree under the taller one, so trees stay O(log n) tall. Path compression makes every element on a find path point straight at the root, so later finds are shorter. Together they make operations nearly constant time.
What is the time complexity of union-find?
With both optimizations, m operations on n elements take O(m α(n)) time, where the inverse Ackermann function α(n) is at most 4 in practice. Without them a single find can take O(n).
How is union-find used in Kruskal's algorithm?
Kruskal sorts the edges by weight and adds an edge only if its ends are in different sets. Union-find answers that question with two finds and records the new edge with a union.
How do you detect a cycle with union-find?
Process the edges of an undirected graph one by one. If both ends of an edge already have the same root, the edge closes a cycle. Otherwise union the two sets.

Related algorithms: Kruskal's MST Algorithm, Connected Components, Borůvka's Algorithm, Cycle Detection

An example graph: you can change it, or start blank.

Zoom Controls

33%
Nodes: 8
Edges: 10