Skip to content
mlmentorship

Reject an undirected edge whose endpoints already share a component

Separate graph paths from representative pointers, then change sparse labels or count remaining components.

Published · 16 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Reject an undirected edge whose endpoints already share a component

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Accept an edge only when its endpoints have different representative roots; otherwise it closes a cycle.

Problem trace

An edge is redundant when its endpoints already share a graph path

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.
node1first2second34parent1234root size1111accepted edgesnone
exampleedges=[[1,2],[3,4],[2,3],[4,2]]currentEdge[1,2]
first
(0, 1)
second
(0, 2)
example
edges=[[1,2],[3,4],[2,3],[4,2]]

Recognize it
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?
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

Path compression changes bookkeeping, not the original graphFinding node 4 redirects its parent from 3 to root 1. The accepted problem edges remain unchanged.Graph edges remain fixed while parentbookkeeping changes1234Before compression: parent of four isthree2->13->14->3After compression: parent of four isone2->13->14->1No new four-one problem edge wasadded.
Derivation
Path compression changes the bookkeeping, not the original graphThe accepted problem graph remains the chain one-two-three-four. Before find four, DSU parents include four to three to one. After compression four points directly to one; two and three still point to one. No accepted graph edge is changed.The accepted problem graph NEVER changeshere1234DSU parents BEFORE find(4)1234AFTER: only parent(4) changes from 3 to 11234
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

Worked example: the closing edge connects nodes already in one componentAfter joining (1,2) and (2,3), nodes 1 and 3 share a representative. Their new edge closes a cycle instead of merging components.An already-connected pair does notremove another componentAfter two earlier successful unions1231 componentsTest 1-3: already in one group1231 components: count unchangedEdge 1-3 closes the existing route;it does not merge two groups.
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

Path compression changes bookkeeping, not the original graphFinding node 4 redirects its parent from 3 to root 1. The accepted problem edges remain unchanged.Graph edges remain fixed while parentbookkeeping changes1234Before compression: parent of four isthree2->13->14->3After compression: parent of four isone2->13->14->1No new four-one problem edge wasadded.
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

Worked example: the closing edge connects nodes already in one componentAfter joining (1,2) and (2,3), nodes 1 and 3 share a representative. Their new edge closes a cycle instead of merging components.An already-connected pair does notremove another componentAfter two earlier successful unions1231 componentsTest 1-3: already in one group1231 components: count unchangedEdge 1-3 closes the existing route;it does not merge two groups.
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.
node1first2second34parent1234root size1111accepted edgesnone
exampleedges=[[1,2],[3,4],[2,3],[4,2]]currentEdge[1,2]
first
(0, 1)
second
(0, 2)
example
edges=[[1,2],[3,4],[2,3],[4,2]]

Recognize it
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 True


def 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 be maximum label plus one. The literal allocation costs , even when only a few distinct labels occur. Path halving and union by size give amortized time and 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 with 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.