Python coding

Extra cable in the network

A network of n computers labelled 1 to n was wired as a tree (connected, no loops) until someone plugged in one extra cable. edges lists every cable as [a, b] in the order it was installed. Return the cable whose removal turns the network back into a tree; if several would work, return the one that appears last in edges, written exactly as it appears there.

The extra cable may duplicate an existing one. Aim for near-linear time.

  • extra_cable(3, [[1,2],[1,3],[2,3]]) → [2,3]
  • extra_cable(5, [[1,2],[2,3],[3,4],[1,4],[1,5]]) → [1,4]
  • extra_cable(5, [[1,2],[2,3],[3,1],[3,4],[4,5]]) → [3,1]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Think in groups of already-connected computers: each cable either merges two groups or joins two computers that were already connected.

Hint 2

Process the cables in order with union-find. The first cable whose ends already have the same root closes the loop, and it is also the last loop cable in the list.

Solution and why it works
pythonO(n·α(n)) · O(n)
def extra_cable(n: int, edges: list[list[int]]) -> list[int]:
    parent = list(range(n + 1))          # nodes are 1..n
    size = [1] * (n + 1)

    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]  # path halving: iterative compression
            x = parent[x]
        return x

    for a, b in edges:
        ra, rb = find(a), find(b)
        if ra == rb:
            return [a, b]                # already connected: this cable closes the loop
        if size[ra] < size[rb]:
            ra, rb = rb, ra
        parent[rb] = ra                  # smaller tree under the larger root
        size[ra] += size[rb]
    return []

Until the loop closes, every cable joins two separate groups, so the union succeeds; the first cable whose ends already share a root closes the only cycle. Every other cable on that cycle came earlier, so it is also the last candidate in the list. Compare roots from find, never parent[a] == parent[b]: a parent is not always the root. Iterative path halving plus union by size keeps each find near-constant without hitting Python's recursion limit.