Redundant Connection

MediumUnion-findLeetCode 684 ↗World 6-18
0:00 / 0:00

A tree got one extra edge that closes a loop. Join nodes with union-find; the first edge whose ends already share a root is the extra one.

▼

The problem

LeetCode 684 (Medium). A tree of n nodes (labelled 1..n) gets one extra edge, so the graph has exactly one loop. Return an edge that can be removed to leave a tree; if several work, return the one that appears last in the input.

The walkthrough example is [[1,2],[3,4],[2,4],[1,4],[4,5]] → [1,4] (new in this version; the original used [[1,2],[2,3],[3,4],[1,4],[1,5]], where every node simply joins 1). It was chosen because it shows more: the loop is 1-2-4, so cutting [3,4] would cut node 3 off (not every edge works); [2,4] merges two real groups root-onto-root (3 under 1, union by rank with equal ranks, rank 1 → 2); and the final find(4) climbs 4 → 3 → 1, so path compression actually happens in the walkthrough (parent[4]: 3 → 1).

def findRedundantConnection(edges):
    parent = list(range(len(edges) + 1))
    rank = [0] * (len(edges) + 1)
    def find(x):
        if parent[x] != x:
            parent[x] = find(parent[x])
        return parent[x]
    for a, b in edges:
        ra, rb = find(a), find(b)
        if ra == rb:
            return [a, b]
        if rank[ra] < rank[rb]:
            ra, rb = rb, ra
        parent[rb] = ra
        if rank[ra] == rank[rb]:
            rank[ra] += 1

Checked against a brute force (remove each edge from the last; the first removal that leaves the graph connected is the answer) on 20,000 random trees of 3 to 12 nodes plus one extra edge, in shuffled order and orientation (Python), and again at load in src/slimes.jsx (solve() against brute() on 400 seeded random cases). The first edge whose ends already share a root is the last loop edge in input order, which is exactly the one the problem asks for. Time about O(n) (each find is amortized inverse Ackermann, nearly constant); space O(n), the parent and rank arrays.

Every value on screen is computed in code: the walkthrough's roots, verdicts, parent / rank cells, arrows and the compression come from solve() (the same algorithm, recording each find's path and the nodes it re-pointed; tableEvents() in src/scenes/S5.jsx replays them and asserts the final arrays); the loop and "the last loop edge" from loopEdges() / brute(); the slow way's visit order (1, 2, 4) from dfsVisit(); the cost scene's arrays (parent 1 1 1 1 5, rank 2 0 1 0 0) from the run's final step; src/gen_score.py mirrors the same cue times.

TRY IT ON LEETCODE ▶

The solution

def findRedundantConnection(edges):
    parent = list(range(len(edges) + 1))
    rank = [0] * (len(edges) + 1)
    def find(x):
        if parent[x] != x:
            parent[x] = find(parent[x])
        return parent[x]
    for a, b in edges:
        ra, rb = find(a), find(b)
        if ra == rb:
            return [a, b]
        if rank[ra] < rank[rb]:
            ra, rb = rb, ra
        parent[rb] = ra
        if rank[ra] == rank[rb]:
            rank[ra] += 1

Transcript

Redundant Connection. You get a tree of n nodes plus one extra edge, so the graph has exactly one loop. Return an edge you can remove to make it a tree again. If several work, return the last one in the input.

Take edges one two, three four, two four, one four, and four five. One, two and four form the loop. Cutting three four would cut node three off, so it can't be the answer. Any loop edge works, and the last one in the list is one four.

The simple way adds edges one by one. Before each, search the graph so far: are its two ends already connected? If they are, this edge closes the loop. But a search can walk every node, and there are n edges, so that's order n squared.

Union-find answers that faster. Every node points to a parent, and following parents leads to its group's root. Find climbs to that root. Union joins two groups by pointing one root at the other. If both ends of an edge already share a root, they're connected, and the edge is redundant.

Let's run it. One two: different roots, so two joins one. Three four: four joins three. Two four: two's root is one, four's root is three. Different, so root three points at root one, and the groups merge. One four: four climbs through three to one. Same root, so one four is redundant. Return it.

In code, every node starts as its own parent. For each edge, find both roots. If they match, return the edge. Otherwise, point one root at the other. Two tricks keep the trees flat. Union by rank hangs the shorter tree under the taller one. And path compression points every node that find passes straight at the root.

With both tricks, each find takes nearly constant time, so the whole run is about order n, not n squared. Space is order n, for the parent and rank arrays.

Same root means already connected. That's Redundant Connection.