◀ THE GRIND — GRAPHS

Redundant Connection

MEDIUM✓ CHIP-TIMEDLC #684 — FULL STATEMENT ↗

The drill: A tree of n nodes had exactly one extra edge added to it, turning it into a graph with n nodes and n edges and exactly one cycle. Find that one extra edge — if more than one edge could be removed to restore a tree, return whichever one appears last in the input.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A graph starts life as a valid tree of n nodes, then gains exactly one extra edge — leaving n nodes and n edges total, and exactly one cycle somewhere in the structure. The task is to identify that one extra edge.

Removing the right edge from the cycle restores a valid tree; several edges along that cycle might work equally well for restoring a tree, so the tie is broken by picking whichever edge appears last in the input order.

The answer is that single edge, given as its two endpoint node numbers, exactly as it appeared in the input list.

EX 01
edges = [[1, 2], [1, 3], [2, 3]]
[2, 3]
A BARE TRIANGLE
EX 02
edges = [[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]
[1, 4]
A SQUARE WITH A HANGING LEAF
EX 03
edges = [[1, 2], [2, 3], [3, 1]]
[3, 1]
SAME TRIANGLE, EDGES IN A DIFFERENT ORDER
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

A tree on n nodes needs exactly n−1 edges. One extra edge means exactly one cycle exists somewhere, and removing the right single edge from that cycle is enough to make everything a tree again.

HINT 2 THE STRUCTURE

The redundant edge is the one connecting two nodes that were already reachable from each other through earlier edges — everything before it was still building a tree cleanly.

HINT 3 ONE STEP FROM THE ANSWER

Walk the edges in order, union each pair's endpoints, and the moment an edge's two endpoints already share a root, that edge is the answer — it's the one closing the cycle.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE EDGE THAT CLOSES THE LOOPPATTERN · UNION-FIND, ONE PASSedges: (1,2) (1,3) (2,3)
STEP 1

Union-find each edge left to right — the first edge whose endpoints already share a root is the redundant one.

STEP 1 / 5 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/redundant-connection.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        n = len(edges)
        parent = list(range(n + 1))

        def find(x):
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        for a, b in edges:
            ra, rb = find(a), find(b)
            if ra == rb:
                return [a, b]
            parent[ra] = rb
        return []
TIME O(E·Α(V))SPACE O(V)PYTHON · RACE PACE · 17 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED