CodeArchon

mediumGraphsGoogle

Spare-Link Finder

A tree-shaped mesh network has one extra cable that creates a cycle. Identify the last-added cable that must be removed.

Given a graph that started as a tree with n nodes and received one extra edge, return the edge (last in input order) that can be removed to restore the tree.

Choose approach

1
2
3
1/3
Narrationstep 1 of 3

Edge (1,2) joins separate components -> keep.

1def findRedundant(edges):
2 n = len(edges)
3 parent = list(range(n + 1))
4 def find(x):
5 while parent[x] != x:
6 parent[x] = parent[parent[x]]; x = parent[x]
7 return x
8 for a, b in edges:
9 ra, rb = find(a), find(b)
10 if ra == rb: return [a, b]
11 parent[ra] = rb
12 return []
Variables
a=1
b=2

How to think about it

  1. Exactly one extra edge over n-1 -> exactly one cycle.
  2. The cycle-closing edge is unique and returned.
  3. Order-of-input semantics are respected by scanning linearly.

Edge cases to catch in interview

  • First edge can be redundant if it creates a self-loop (not usually in problem).
  • Guaranteed exactly one extra edge.

Examples

Example 1[1,4]
{"edges":[[1,2],[2,3],[3,4],[1,4],[1,5]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed