LeetCode #684 Medium

Redundant Connection

Redundant Connection is LeetCode 684 (Medium). A tree with n nodes labelled 1 to n had one extra edge added, so the undirected graph in edges now contains exactly one cycle.

  • Return an edge you can remove so that the rest is a tree of all n nodes.
  • If several edges work, return the one that appears last in edges.
Constraints
  • n == edges.length
  • 3 <= n <= 1000
  • edges[i].length == 2
  • 1 <= ai < bi <= edges.length
  • ai != bi
  • There are no repeated edges.
  • The given graph is connected.
graphunion-find
Open on LeetCode ↗
02

Intuition

Add the edges one at a time and keep track of which nodes are already connected. An edge between two nodes that are already connected gives them a second path, so it is the edge that closes the cycle.

  • Tracking groups: union find stores each connected group as a small tree of parent links. Two nodes are connected exactly when their walks up the links end at the same root.
  • Why it is the last valid edge: the cycle only exists once all of its edges are present, so the edge that completes it is the latest cycle edge in the list.
How to spot this pattern

"Edges arrive one by one; find the first one that joins two nodes already connected" is the union find signature. The same check builds Kruskal's minimum spanning tree, where an edge whose ends share a root is skipped instead of returned.

03

Approach

Try it first

Before reading on, decide how you would know, at the moment an edge arrives, that its two ends are already connected. Then convince yourself why the first edge that fails that test is also the last edge on the cycle. Aim for close to O(n).

1

Give every node its own group

Set parent[i] = i and size[i] = 1 for every label. Before any edge is read, no two nodes are connected, so each node is the root of a group of one.

2

Find the root of both ends

For edge [u, v], follow parent links from u until a node points to itself, then do the same from v. While walking, point each node at its grandparent; this path halving keeps later walks short.

3

Same root: return the edge

If both walks end at the same root, earlier edges already connect u and v, so this edge closes the cycle. Return it straight away; no later edge needs to be read.

4

Different roots: join the groups

Point the root of the smaller group at the root of the larger one and add the sizes. Hanging the smaller tree under the bigger one keeps every tree shallow, so each walk stays short.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def findRedundantConnection(self, edges):
▶3 parent = list(range(len(edges) + 1))
▶4 size = [1] * (len(edges) + 1)
▶5 
▶6 def find(x):
▶7 while parent[x] != x:
▶8 parent[x] = parent[parent[x]]
▶9 x = parent[x]
▶10 return x
▶11 
▶12 for u, v in edges:
▶13 ru, rv = find(u), find(v)
▶14 if ru == rv:
▶15 return [u, v]
▶16 if size[ru] < size[rv]:
▶17 ru, rv = rv, ru
▶18 parent[rv] = ru
▶19 size[ru] += size[rv]
▶20 return []
123parent1node 12node 23node 3root of uroot of vevery node starts as its own root
parent[1, 2, 3]nodes 1 to 3
Edges are read in the order given. Before any edge is added, each node is a group of one, so every node is its own parent. The dashed lines are edges not checked yet.
123parent1node 12node 23node 3root of 11root of 22edge 1–2: roots 1 and 2
edge[1, 2]edge 1 of 3
roots1, 2different groups
Follow parent links from 1 and from 2 until a node points to itself; that node is the root that names the group. The roots differ, so no earlier edges join 1 and 2.
123parent1node 11node 23node 3root of 11root of 22different roots → 2 now points to 1
parent[2]1groups joined
group size2under root 1
Join the two groups by pointing root 2 at root 1. The groups are the same size, so either root could go on top. The edge stays in the tree.
123parent1node 11node 23node 3root of 11root of 33edge 1–3: roots 1 and 3
edge[1, 3]edge 2 of 3
roots1, 3different groups
Follow parent links from 1 and from 3 until a node points to itself; that node is the root that names the group. The roots differ, so no earlier edges join 1 and 3.
123parent1node 11node 21node 3root of 11root of 33different roots → 3 now points to 1
parent[3]1groups joined
group size3under root 1
Join the two groups by pointing root 3 at root 1. The smaller group goes under the larger one, which keeps the walks short. The edge stays in the tree.
123parent1node 11node 21node 3root of 22→1root of 33→1edge 2–3: both reach root 1
edge[2, 3]edge 3 of 3
roots1, 1same group
Follow parent links from 2 and from 3 until a node points to itself; that node is the root that names the group. Both walks end at 1, so 2 and 3 are already joined by earlier edges.
123parent1node 11node 21node 3root of 22→1root of 33→1same root → 2–3 closes the loop → answer
result[2, 3]
A path from 2 to 3 already exists, so this edge makes a loop. Every other edge on that loop came earlier in the list, so this one is the last of them and is the answer.
05

Common pitfalls

Linking the nodes instead of their roots

✗ Wrong
if find(u) != find(v):
    parent[u] = v
✓ Right
ru, rv = find(u), find(v)
if ru != rv:
    parent[rv] = ru

Overwriting parent[u] pulls u out of its old group instead of merging the two groups. On [[1,2],[1,3],[2,3]], node 1 first points to 2, then to 3, so 2 and 3 never share a root and the cycle edge [2,3] is missed.

Sizing the parent array to n

✗ Wrong
parent = list(range(len(edges)))
✓ Right
parent = list(range(len(edges) + 1))

Nodes are labelled 1 to n, so the array needs index n. With [[1,2],[1,3],[2,3]], looking up node 3 in a 3-slot array raises an index error.

06

Edge cases

The answer is not the last edge in the input

For [[1,2],[2,3],[3,4],[1,4],[1,5]] the answer is [1,4]. Edge [1,5] comes later, but it is not on the cycle: removing it would cut node 5 off. The loop returns at [1,4] before reading it.

07

Complexity

Time
O(n · α(n))
Space
O(n)
n is the number of edges, which equals the number of nodes. Each edge does two root walks, and with path halving plus union by size a walk costs α(n) on average, the inverse Ackermann function, which is below 5 for any real input. The parent and size arrays hold n + 1 entries.
08

Redundant Connection FAQ

Can it be solved with DFS?

Yes. Before adding each edge [u, v], run a DFS from u over the edges added so far; if it reaches v, return the edge. That is O(n²), which passes for 1,000 edges. A faster DFS finds the cycle's nodes once, then scans edges from the end and returns the first edge with both ends on the cycle.

Do I need both path halving and union by size?

Either one alone already gives O(log n) per walk, which is fast enough here. Together they bring the cost down to α(n). Without either, a chain like [[1,2],[2,3],[3,4],…] can turn the parent links into one long line, and each walk costs O(n).

How is Redundant Connection II different?

LeetCode 685 makes the edges directed: the input was a rooted tree, and the extra edge can give a node two parents. You first look for a node with two incoming edges, then use union find to decide which of those two edges, or which cycle edge, to remove.