Algorithm patterns← All patterns

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.

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
0
1
1
2
2
3
3
4
4
5
5

groups (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.

1 / 10
solution.ts
1function findRedundantConnection(edges: number[][]): number[] {
2 const parent = Array.from({ length: edges.length + 1 }, (_, i) => i);
3 const find = (x: number): number =>
4 parent[x] === x ? x : (parent[x] = find(parent[x]));
5 for (const [a, b] of edges) {
6 const ra = find(a), rb = find(b);
7 if (ra === rb) return [a, b];
8 parent[ra] = rb;
9 }
10 return [];
11}

Practice next