cswork / templatesOpen the Line 500 list

STOP 15 · GRAPHS

Graph Connectivity and Union-Find

Union-find with path compression and union by size ≈ O(α(n)) per operation

Contest ratings Rating 1412–Rating 2085· median Rating 1715(9 of 16 problems rated by zerotrac)

Open the Line 500 list · stop 15 · 16 problems
Learn first
Leads to
How often asked
asked by 7 companies · in 10 reportsTikTok / ByteDance 3, Amazon 2, Apple 1, Electronic Arts 1, Mercor 1

Warm up with this one

LC 1971Find if Path Exists in GraphEasy
Stuck? Peek at the approach

Build adjacency lists from edges and determine whether two nodes are connected.

Key points

  1. Compress paths in find and hang the smaller tree under the larger in union; together each operation is close to constant time.
  2. union returning false means the two ends were already connected, which is how you detect cycles and redundant edges.
  3. Keep per-component data such as size only on the root and add it up when merging.

Common pitfalls

  • parent[a] == parent[b] does not mean connected; compare find(a) == find(b).
  • Writing parent[a] = b instead of linking the two roots corrupts the structure.
  • When nodes are strings or coordinates, map them to 0..n-1 first, or keep parent in a hash map.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Union-find · union by size + path compression

8 elements, 7 unions in order

01234567
0p[0]
1p[1]
2p[2]
3p[3]
4p[4]
5p[5]
6p[6]
7p[7]
CurrentDiscovered / computedAnswer
Components
8
Operation
—

Every element starts alone: parent[i] = i. Arrows point from a child to its parent; nodes without one are roots.

InvariantElements of one set reach the same root through parent; trees stay O(log n) tall and nearly flat after compression.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 1971, with it.

Python
class DSU:
    def __init__(self, n: int):
        self.parent = list(range(n))
        self.size = [1] * n
        self.count = n  # number of components

    def find(self, x: int) -> int:
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            x = self.parent[x]
        return x

    def union(self, a: int, b: int) -> bool:
        a, b = self.find(a), self.find(b)
        if a == b:
            return False  # already connected: this edge would close a cycle
        if self.size[a] < self.size[b]:
            a, b = b, a
        self.parent[b] = a  # hang the smaller tree under the larger
        self.size[a] += self.size[b]
        self.count -= 1
        return True
C++
struct DSU {
    vector<int> parent, size;
    int count;  // number of components

    DSU(int n) : parent(n), size(n, 1), count(n) { iota(parent.begin(), parent.end(), 0); }

    int find(int x) {
        while (parent[x] != 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 connected: this edge would close a cycle
        if (size[a] < size[b]) swap(a, b);
        parent[b] = a;  // hang the smaller tree under the larger
        size[a] += size[b];
        count--;
        return true;
    }
};
Java
class DSU {
    private final int[] parent, size;
    int count; // number of components

    DSU(int n) {
        parent = new int[n];
        size = new int[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            size[i] = 1;
        }
        count = n;
    }

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

    boolean union(int a, int b) {
        a = find(a);
        b = find(b);
        if (a == b) return false; // already connected: this edge would close a cycle
        if (size[a] < size[b]) {
            int t = a;
            a = b;
            b = t;
        }
        parent[b] = a; // hang the smaller tree under the larger
        size[a] += size[b];
        count--;
        return true;
    }
}
Go
type DSU struct {
	parent, size []int
	count        int // number of components
}

func NewDSU(n int) *DSU {
	d := &DSU{parent: make([]int, n), size: make([]int, n), count: n}
	for i := range d.parent {
		d.parent[i], d.size[i] = i, 1
	}
	return d
}

func (d *DSU) Find(x int) int {
	for d.parent[x] != x {
		d.parent[x] = d.parent[d.parent[x]] // path halving
		x = d.parent[x]
	}
	return x
}

func (d *DSU) Union(a, b int) bool {
	a, b = d.Find(a), d.Find(b)
	if a == b {
		return false // already connected: this edge would close a cycle
	}
	if d.size[a] < d.size[b] {
		a, b = b, a
	}
	d.parent[b] = a // hang the smaller tree under the larger
	d.size[a] += d.size[b]
	d.count--
	return true
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Two-colouring by BFS for bipartitenessO(V + E) time · O(V) space

When nodes must split into two groups with every edge crossing between them (bipartite graphs, keeping people who dislike each other apart): BFS paints neighbours opposite colours, and a neighbour with the same colour means an odd cycle, so the answer is no. The graph may be disconnected, so every uncoloured node starts its own search. LC 785 (Is Graph Bipartite?), LC 886 (Possible Bipartition).

Python
from collections import deque


def is_bipartite(graph: list[list[int]]) -> bool:
    """Can the nodes be 2-coloured so every edge joins different colours? (LC 785)"""
    color = [-1] * len(graph)
    for s in range(len(graph)):  # every component, not only the one holding node 0
        if color[s] != -1:
            continue
        color[s] = 0
        q = deque([s])
        while q:
            u = q.popleft()
            for v in graph[u]:
                if color[v] == -1:
                    color[v] = color[u] ^ 1  # the other colour
                    q.append(v)
                elif color[v] == color[u]:
                    return False  # an odd cycle
    return True
C++
// Can the nodes be 2-coloured so every edge joins different colours? (LC 785)
bool isBipartite(const vector<vector<int>>& graph) {
    vector<int> color(graph.size(), -1);
    for (int s = 0; s < (int)graph.size(); s++) {  // every component, not only the one holding node 0
        if (color[s] != -1) continue;
        color[s] = 0;
        queue<int> q;
        q.push(s);
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            for (int v : graph[u]) {
                if (color[v] == -1) {
                    color[v] = color[u] ^ 1;  // the other colour
                    q.push(v);
                } else if (color[v] == color[u]) {
                    return false;  // an odd cycle
                }
            }
        }
    }
    return true;
}
Java
class Solution {
    // Can the nodes be 2-coloured so every edge joins different colours? (LC 785)
    boolean isBipartite(int[][] graph) {
        int[] color = new int[graph.length];
        Arrays.fill(color, -1);
        for (int s = 0; s < graph.length; s++) { // every component, not only the one holding node 0
            if (color[s] != -1) continue;
            color[s] = 0;
            Deque<Integer> q = new ArrayDeque<>(List.of(s));
            while (!q.isEmpty()) {
                int u = q.poll();
                for (int v : graph[u]) {
                    if (color[v] == -1) {
                        color[v] = color[u] ^ 1; // the other colour
                        q.offer(v);
                    } else if (color[v] == color[u]) {
                        return false; // an odd cycle
                    }
                }
            }
        }
        return true;
    }
}
Go
// isBipartite reports whether the nodes can be 2-coloured so every edge joins different colours.
func isBipartite(graph [][]int) bool {
	color := make([]int, len(graph))
	for i := range color {
		color[i] = -1
	}
	for s := range graph { // every component, not only the one holding node 0
		if color[s] != -1 {
			continue
		}
		color[s] = 0
		q := []int{s}
		for len(q) > 0 {
			u := q[0]
			q = q[1:]
			for _, v := range graph[u] {
				if color[v] == -1 {
					color[v] = color[u] ^ 1 // the other colour
					q = append(q, v)
				} else if color[v] == color[u] {
					return false // an odd cycle
				}
			}
		}
	}
	return true
}
Tarjan bridges: low cannot climb past the parentO(V + E) time · O(V + E) space

To find edges (or nodes) whose removal disconnects the graph, such as critical connections or articulation points: DFS records each node's discovery time disc, and low is the earliest discovery time its subtree reaches through one back edge. When a child v has low[v] > disc[u], the edge u-v is a bridge. LC 1192 (Critical Connections in a Network). Deep graphs need a higher recursion limit in Python.

Python
def critical_connections(n: int, connections: list[list[int]]) -> list[list[int]]:
    """Every bridge, an edge whose removal disconnects the graph (LC 1192)."""
    graph = [[] for _ in range(n)]
    for u, v in connections:
        graph[u].append(v)
        graph[v].append(u)
    disc = [0] * n  # discovery time; 0 = not visited yet
    low = [0] * n  # earliest discovery time the subtree reaches with one back edge
    timer = 1
    res = []

    def dfs(u: int, parent: int) -> None:
        nonlocal timer
        disc[u] = low[u] = timer
        timer += 1
        for v in graph[u]:
            if v == parent:
                continue  # assumes no parallel edges
            if disc[v]:
                low[u] = min(low[u], disc[v])  # a back edge
            else:
                dfs(v, u)
                low[u] = min(low[u], low[v])
                if low[v] > disc[u]:  # v's subtree cannot climb above u without this edge
                    res.append([u, v])

    for s in range(n):
        if not disc[s]:
            dfs(s, -1)
    return res
C++
// Every bridge, an edge whose removal disconnects the graph (LC 1192).
vector<pair<int, int>> criticalConnections(int n, const vector<pair<int, int>>& connections) {
    vector<vector<int>> graph(n);
    for (auto [u, v] : connections) {
        graph[u].push_back(v);
        graph[v].push_back(u);
    }
    vector<int> disc(n, 0), low(n, 0);  // disc 0 = not visited; low: earliest time reached with one back edge
    int timer = 1;
    vector<pair<int, int>> res;
    function<void(int, int)> dfs = [&](int u, int parent) {
        disc[u] = low[u] = timer++;
        for (int v : graph[u]) {
            if (v == parent) continue;  // assumes no parallel edges
            if (disc[v]) {
                low[u] = min(low[u], disc[v]);  // a back edge
            } else {
                dfs(v, u);
                low[u] = min(low[u], low[v]);
                if (low[v] > disc[u]) res.push_back({u, v});  // v's subtree cannot climb above u without this edge
            }
        }
    };
    for (int s = 0; s < n; s++)
        if (!disc[s]) dfs(s, -1);
    return res;
}
Java
class Solution {
    private List<List<Integer>> graph;
    private int[] disc, low; // disc 0 = not visited; low: earliest time reached with one back edge
    private int timer;
    private List<int[]> res;

    // Every bridge, an edge whose removal disconnects the graph (LC 1192).
    List<int[]> criticalConnections(int n, int[][] connections) {
        graph = new ArrayList<>();
        for (int i = 0; i < n; i++) graph.add(new ArrayList<>());
        for (int[] e : connections) {
            graph.get(e[0]).add(e[1]);
            graph.get(e[1]).add(e[0]);
        }
        disc = new int[n];
        low = new int[n];
        timer = 1;
        res = new ArrayList<>();
        for (int s = 0; s < n; s++)
            if (disc[s] == 0) dfs(s, -1);
        return res;
    }

    private void dfs(int u, int parent) {
        disc[u] = low[u] = timer++;
        for (int v : graph.get(u)) {
            if (v == parent) continue; // assumes no parallel edges
            if (disc[v] != 0) {
                low[u] = Math.min(low[u], disc[v]); // a back edge
            } else {
                dfs(v, u);
                low[u] = Math.min(low[u], low[v]);
                if (low[v] > disc[u]) res.add(new int[] {u, v}); // v's subtree cannot climb above u without this edge
            }
        }
    }
}
Go
// criticalConnections returns every bridge, an edge whose removal disconnects the graph (LC 1192).
func criticalConnections(n int, connections [][2]int) [][2]int {
	graph := make([][]int, n)
	for _, e := range connections {
		graph[e[0]] = append(graph[e[0]], e[1])
		graph[e[1]] = append(graph[e[1]], e[0])
	}
	disc, low := make([]int, n), make([]int, n) // disc 0 = not visited; low: earliest time reached with one back edge
	timer := 1
	var res [][2]int
	var dfs func(u, parent int)
	dfs = func(u, parent int) {
		disc[u], low[u] = timer, timer
		timer++
		for _, v := range graph[u] {
			if v == parent {
				continue // assumes no parallel edges
			}
			if disc[v] != 0 {
				low[u] = min(low[u], disc[v]) // a back edge
			} else {
				dfs(v, u)
				low[u] = min(low[u], low[v])
				if low[v] > disc[u] { // v's subtree cannot climb above u without this edge
					res = append(res, [2]int{u, v})
				}
			}
		}
	}
	for s := 0; s < n; s++ {
		if disc[s] == 0 {
			dfs(s, -1)
		}
	}
	return res
}

Why it works

  1. Each set is a tree whose root represents it; find returns the root, so two nodes share a root exactly when they are in the same component. union only hangs one root under another, so it never breaks an existing connection.
  2. Union by size keeps trees O(log n) tall: every time a node's tree gets deeper, the size of its set at least doubles, which can happen only log n times. Adding path compression brings the amortised cost close to constant, α(n).
  3. union returning false means the endpoints were already connected, so the edge would close a cycle, which is how redundant edges are detected.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
动态连通性我用并查集。每个集合是一棵树,根是代表元,两点同根就说明连通。find 时做路径压缩,union 时把小树挂到大树下,按大小合并保证树高 O(log n),两者一起均摊接近常数。如果 union 发现两点已经同根,说明这条边会成环,可以直接用来判冗余边。
English
For dynamic connectivity I use union-find. Each set is a tree whose root represents it, and two nodes are connected exactly when they share a root. find compresses paths and union hangs the smaller tree under the larger, which keeps trees logarithmic, and together they cost nearly constant time amortised. If union finds both ends already share a root, the edge would close a cycle, which detects redundant edges directly.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

5 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

5 questions
  1. With both path compression and union by rank (or size), what is the amortized time per union-find operation?
  2. Detecting a cycle in an undirected graph with union-find, edge by edge: when does edge (u, v) close a cycle?
  3. After m edges on n vertices, union-find made s successful unions (the ends were in different sets). How many connected components are there?
  4. m find or union calls on n elements (m >= n). What is the total time?
    def find(p, x):
        while p[x] != x:
            p[x] = p[p[x]]
            x = p[x]
        return x
    
    def union(p, size, a, b):
        a, b = find(p, a), find(p, b)
        if a == b:
            return False
        if size[a] < size[b]:
            a, b = b, a
        p[b] = a
        size[a] += size[b]
        return True
  5. m find or union calls on n elements. What is the worst-case total time?
    def find(p, x):
        while p[x] != x:
            x = p[x]
        return x
    
    def union(p, a, b):
        p[find(p, a)] = find(p, b)

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

class DSU:
    def __init__(self, n: int):
        self.parent = list(range(n))
        self.size = [1] * n
        self.count = n
        self.size[a] += self.size[b]
        self.count -= 1
        return True

Practice by stage

This stop's 16 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 4

#ProblemApproachRating
1971Find if Path Exists in GraphBuild adjacency lists from edges and determine whether two nodes are connected.
841Keys and RoomsModel room keys as directed edges and check whether every node is reachable from the start.Rating 1412
547Number of ProvincesCount connected components from an adjacency matrix, comparing traversal with union-find.
323Number of Connected Components in an Undirected Graph 🔒Count undirected connected components from an edge list, including isolated nodes.

Core 10

#ProblemApproachRating
261Graph Valid Tree 🔒Check both connectivity and absence of cycles to decide whether an undirected graph is a tree.
684Redundant ConnectionUnion sets in edge order and identify the first redundant edge joining already connected nodes.
1319Number of Operations to Make Network ConnectedRelate spare edges to the number of components to determine the minimum operations needed to connect the graph.Rating 1633
785Is Graph BipartiteTwo-color every connected component and detect conflicts caused by odd cycles.Rating 1625
886Possible BipartitionModel mutual exclusions as bipartite-graph constraints.Rating 1795
721Accounts MergeUse shared email addresses to define equivalence, merge accounts, and organize deduplicated output.
1202Smallest String With SwapsUse swap relationships to partition positions into components, then sort and rearrange characters within each component.Rating 1855
2101Detonate the Maximum BombsBuild a directed graph from blast radii and search from each start to find the largest reachable set.Rating 1880
1466Reorder Routes to Make All Paths Lead to the City ZeroRetain original edge directions during an undirected traversal and count edges that must be reversed.Rating 1634
2359Find Closest Node to Given Two NodesExploit the at-most-one-successor structure to compare reachable distances from two starting nodes.Rating 1715

Advanced 2

#ProblemApproachRating
399Evaluate DivisionRepresent ratios as weighted edges, compose them along paths, and handle unknown variables.
1192Critical Connections in a NetworkIdentify bridges with DFS timestamps and low-link values, explaining how back edges affect connectivity.Rating 2085

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.