← Visualizers
Graphs · 1.F / 2.E · the union-find atom LeetCode 684

Redundant Connection / visualized

n nodes, n edges — a tree plus exactly one extra. Walk the edges in order and ask one question of each: are these two ends already in the same component? The first edge for which the answer is yes is the redundant one. The structure that answers it is a forest of parent pointers, drawn here beside the graph, so that find climbing to a root and union re-rooting are things you watch rather than infer.

Execution

idle
INVARIANT Union-Find Cycle Invariant: A tree with n nodes has exactly n-1 edges. The first edge (u, v) where find(u) == find(v) completes a cycle and is the redundant connection. Path compression and union-by-rank guarantee near-O(1) amortized inverse Ackermann α(n) time per edge.
the graph · edges as given
the DSU forest · parent pointers
Press Run to begin.
0 / 0
Speed

Java · running line

endpoint u endpoint v where find is standing set root / united edge edge not yet considered
INTERVIEW SCRIPT

How to Explain Redundant Connection to an Interviewer

1. Tree Definition & Over-specification

"A valid tree with $n$ vertices has exactly $n-1$ edges and 0 cycles. Since the input gives $n$ edges, exactly one edge must be creating a cycle."

2. Disjoint Set Union (DSU)

"Initialize each vertex in its own component (parent[i] = i). For each edge (u, v), find their root representatives. If find(u) == find(v), they already belong to the same component—this edge creates the cycle!"

3. Why Union-Find over DFS?

"DFS would require running a search for each edge ($O(n^2)$ total). Union-Find checks connectivity and merges in near-$O(1)$ amortized time ($O(n \cdot \alpha(n))$ overall)."

4. Path Compression & Union by Rank

"Path compression flattens the tree during find: parent[x] = find(parent[x]). Union by rank/size hangs smaller trees under larger roots, preventing degenerating into chains."

O(n·α(n)) time, O(n) space — effectively linear  ·  union by size and path compression are not tuning. Drop them and find walks a chain instead of a stub: the same answer, arrived at in O(n²). Flip the toggle and read the two numbers in the second card.