Pattern 10 / 10 · Advanced
Union-Find
Every group has one leader; joining two groups means one leader follows the other.
The idea
Each node points to a parent; following parents leads to the group's root. Two nodes are connected exactly when they share a root. To join groups, point one root at the other. Path compression makes later finds almost O(1).
time ≈ O(n · α(n)), nearly linearspace O(n)
Reach for it when
- Edges arrive one by one and you ask “are these two already connected?”.
- Counting groups, provinces or components in an undirected graph.
- Detecting the edge that closes a cycle.
Watch it run
684. Redundant Connection
A tree got one extra edge. Return the edge you can remove so the graph is a tree again.
MediumOpen on LeetCode ↗
Example 1
Input: edges = [[1, 2], [1, 3], [2, 3]]
Output: [2, 3]
Example 2
Input: edges = [[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]
Output: [1, 4]
WALKTHROUGH INPUT · edges = [[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]
edges
[1, 2][2, 3][3, 4][1, 4][1, 5]
parent[x] (x below)
0
01
12
23
34
45
5groups (by root)
root 1: {1}root 2: {2}root 3: {3}root 4: {4}root 5: {5}
Every node starts as its own group: parent[x] = x.
1function findRedundantConnection(edges: number[][]): number[] {2const parent = Array.from({ length: edges.length + 1 }, (_, i) => i);3const find = (x: number): number =>4parent[x] === x ? x : (parent[x] = find(parent[x]));5for (const [a, b] of edges) {6const ra = find(a), rb = find(b);7if (ra === rb) return [a, b];8parent[ra] = rb;9}10return [];11}