Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Redundant Connection

MediumLeetCode 684 ↗

The problem, in one line. A network that should be a tree has exactly one extra link. Return the link that can be removed, and if several qualify, the one that comes last in the list. LeetCode 684.

The tell. Links arrive in order and the question is “does this one close a loop?”. A link closes a loop exactly when its two ends were already connected before it arrived, and that is a single union-find question.

The wrong first idea

Keep a list of points that already have a link. If a new link joins two points that are both on the list, call it the extra one.

On [[1,2],[3,4],[2,3],[4,1]] it blames [2,3], because points 2 and 3 were both seen. But 1-2 and 3-4 were separate pairs, and [2,3] is what joined them. The real extra link is [4,1]. Having a link somewhere is not the same as being reachable from each other. The clinic Clinic #26: Redundant Connection builds this out of a cable crew, and this card is its one-page summary.

The invariant

Read the links in order. Before each one, ask for the top of each end’s group.

[1,2]  tops 1, 2 differ: merge
[2,3]  tops differ: merge
[3,4]  tops differ: merge
[1,4]  both tops are the same: this closes the loop, answer

The sentence that stays true every step: find(a) == find(b) exactly when a and b can already reach each other through the links read so far. The first link that fails that test is the last one needed to close the only loop.

The solution

def redundant(edges):
    parent = list(range(len(edges) + 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:                    # already in one group, so this edge closes a loop
            return [a, b]
        parent[ra] = rb
    return []

print(redundant([[1, 2], [2, 3], [3, 4], [1, 4], [1, 5]]))
print(redundant([[1, 2], [3, 4], [2, 3], [4, 1]]))
print(redundant([[1, 2], [1, 3], [2, 3]]))
[1, 4]
[4, 1]
[2, 3]
func redundant(edges [][]int) []int {
	parent := make([]int, len(edges)+1)
	for i := range parent {
		parent[i] = i
	}
	find := func(x int) int {
		for parent[x] != x {
			parent[x] = parent[parent[x]]
			x = parent[x]
		}
		return x
	}
	for _, e := range edges {
		ra, rb := find(e[0]), find(e[1])
		if ra == rb { // already in one group, so this edge closes a loop
			return e
		}
		parent[ra] = rb
	}
	return nil
}

Same three calls print [1 4], [4 1], [2 3].

Complexity

  • Time O(n), times a tiny inverse-Ackermann factor: one pass over the links with a near-constant climb for each.
  • Space O(n): one pointer per point.

Traps

  • Blaming a link whose ends merely appeared before. The input [[1,2],[3,4],[2,3],[4,1]] exposes it, as above.
  • Linking the ends instead of their tops: parent[a] = b. On [[1,2],[1,3],[2,3]] that returns nothing at all, because the old pointers are cut.
  • Returning any link on the loop. In the first call [1,2] is on the loop too, but the answer is the last link read, [1,4].

Next in the ladder

Satisfiability of Equality Equations uses the same merge, but the points are letters, and half the facts are “these must stay apart”.