The Cable That Closes a Loop

Medium · Union-Find · about 20 min

A campus has n buildings numbered 0 to n - 1. Network cables are laid one at a time, in the order of the list cables; each [a, b] is a two-way cable between buildings a and b.

Return the first cable in the list that joins two buildings that were already connected by earlier cables (directly or through other buildings), so it closes a loop. A cable from a building to itself also closes a loop. Return the cable exactly as it appears in the input. If no cable closes a loop, return [].

Example:

first_loop_cable(5, [[0, 1], [1, 2], [2, 3], [1, 3], [0, 4]]) → [1, 3]

Hints

  • Keep a union-find over the buildings and add the cables in order.
  • Before you join a cable's ends, compare their leaders. Equal leaders mean the buildings were already connected.
  • Stop at the first such cable and return it unchanged.

Learn the pattern first: the Union-Find lesson.

More Union-Find problems