Undirected edges arrive incrementally and each needs an already-connected cycle check.
Keep true
Following parent links reaches one representative per component; size is authoritative at roots, and accepted edges join only different roots.
Reuse it
Compare roots before adding connectivity, attach the smaller tree under the larger, and compress paths during find.
Nodes 1..4 each parent themselves and each root has size 1. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which existing graph path makes 4-2 redundant? Why is a compressed parent pointer not necessarily a graph edge?
Sources and provenance
Full interview answer 16 min read
Find the first arriving undirected edge whose addition would create a cycle among previously accepted edges.
Problem
Input. An ordered list edges of undirected endpoint pairs using nonnegative integer labels.
Output. Return the first edge whose endpoints are already connected by previously accepted edges, or [] if none exists.
Rules. Process edges in their given order without changing the list.
A self-loop or repeated connection can be the rejected edge.
This reports one first cycle-closing edge, not every cycle edge in a general graph.
Under the usual tree-plus-one-edge assumption, it is the last arriving edge of that cycle.
Example.[[1, 2], [3, 4], [2, 3], [4, 2]] returns [4, 2].
The previously accepted edges already connect 4 to 2 through 3.
Picture
Each component has one representative root.
Following parent pointers finds that root; only roots have authoritative component sizes.
After the first three edges, the two size-two components have merged under root 1.
Reference drawing
Path compression changes the bookkeeping, not the original graph
Derivation
The top graph is unchanged. Only the parent pointer for 4 shortens after find. A DSU parent arrow is not an accepted problem-graph edge.
Read it this way:Finding node 4 redirects its parent from 3 to root 1. The accepted problem edges remain unchanged. Does redirecting four’s parent add edge four-one to the original problem graph?
Read it this way: plain links are accepted graph edges.
Arrows are DSU parent pointers, not input edges.
For example, parent link 3 -> 1 does not assert an accepted edge between those graph nodes.
find(4) halves 4 -> 3 -> 1 into 4 -> 1.
find(2) also returns 1, so adding [4,2] would close the existing graph path.
Problem trace
An edge is redundant when its endpoints already share a graph path
Read it this way:After joining (1,2) and (2,3), nodes 1 and 3 share a representative. Their new edge closes a cycle instead of merging components. Can joining endpoints already in the same enclosure reduce the component count again?
Path compression changes the bookkeeping, not the original graph
Read it this way:Finding node 4 redirects its parent from 3 to root 1. The accepted problem edges remain unchanged. Does redirecting four’s parent add edge four-one to the original problem graph?
Reference drawing
Problem trace
An edge is redundant when its endpoints already share a graph path
Execution trace
Input and goalFind the edge that creates a cycle in an undirected graph.
Initialize singleton componentsNodes 1..4 each parent themselves and each root has size 1.
Undirected edges arrive incrementally and each needs an already-connected cycle check.
Keep true
Following parent links reaches one representative per component; size is authoritative at roots, and accepted edges join only different roots.
Reuse it
Compare roots before adding connectivity, attach the smaller tree under the larger, and compress paths during find.
Nodes 1..4 each parent themselves and each root has size 1. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which existing graph path makes 4-2 redundant? Why is a compressed parent pointer not necessarily a graph edge?
Read it this way:After joining (1,2) and (2,3), nodes 1 and 3 share a representative. Their new edge closes a cycle instead of merging components. Can joining endpoints already in the same enclosure reduce the component count again?
If roots differ, merge their components by attaching the smaller root tree under the larger.
Add their sizes at the surviving root.
If roots match, return False without merging.
Nonroot size entries can be stale; they are not component summaries.
Code
class DisjointSet: def __init__(self, size: int) -> None: self.parent = list(range(size)) self.component_size = [1] * size def find(self, node: int) -> int: while node != self.parent[node]: self.parent[node] = self.parent[self.parent[node]] node = self.parent[node] return node def union(self, first: int, second: int) -> bool: first_root = self.find(first) second_root = self.find(second) if first_root == second_root: return False if self.component_size[first_root] < self.component_size[second_root]: first_root, second_root = second_root, first_root self.parent[second_root] = first_root self.component_size[first_root] += self.component_size[second_root] return Truedef find_redundant_connection(edges: list[list[int]]) -> list[int]: if not edges: return [] groups = DisjointSet(max(max(edge) for edge in edges) + 1) for first, second in edges: if not groups.union(first, second): return [first, second] return []
Let L be maximum label plus one.
The literal allocation costs O(L), even when only a few distinct labels occur.
Path halving and union by size give O(L+Eα(L)) amortized time and O(L) storage.
The inverse-Ackermann factor is not a literal constant-time guarantee per operation.
Failure Check
Compare roots, not immediate parents.
Ordinary DSU does not support arbitrary edge deletion or directed-cycle detection.
Recovering an actual path requires separate accepted graph edges; compressed parent links are not that evidence.
Change the Label Range
New task: Integer labels are sparse and very large.
Picture and change: Map the distinct labels to dense indices, but return original edge labels.
Reuse the supplied DisjointSet above.
def redundant_sparse_labels(edges): labels = {label for edge in edges for label in edge} indices = {label: index for index, label in enumerate(labels)} groups = DisjointSet(len(indices)) for first, second in edges: if not groups.union(indices[first], indices[second]): return [first, second] return []
Check:[[1000000,9000000],[9000000,7000000],[7000000,1000000]] returns [7000000,1000000].
Allocate three representatives, not nine million.
Expected hashing plus DSU work is O(V+Eα(V)) with O(V) state for distinct labels.
Use when: Vertex population, not label magnitude, should determine allocation.
Change the Aggregate
New task: Count final components in the explicit universe 0..node_count-1.
Picture and change: Start with one component per node.
Only successful unions reduce the count; isolated nodes remain represented.
def component_count(node_count, edges): groups = DisjointSet(node_count) count = node_count for first, second in edges: if groups.union(first, second): count -= 1 return count
Check: Five nodes with [[0,1],[1,2],[2,0],[3,4]] return 2.
Three nodes and no edges return 3.
The cycle edge does not decrease the count.
Require a nonnegative node count and valid endpoints.
Use when: Remaining connectivity matters, not the first rejection.
Transfer Check
Why can compressed parent links not reconstruct an original graph path?
Answer
They record component representation and can skip or replace several accepted edges.
Keep the accepted-edge graph separately when a path witness is required.