Ctrl K

The Extra Cable

Medium
An office has n computers numbered 1 to n. At first they were wired so that any two had exactly one path between them, forming a tree. Then someone ran one more cable between two computers that had not been directly connected. The list cables of length n holds every cable: cables[i] = [a, b] links computers a and b. Return a cable whose removal turns the network back into a tree over all n computers. If several cables qualify, return the one that comes last in the list. Return the cable exactly as it is written in cables.
Example 1
cables=[[2, 3], [1, 2], [3, 4], [1, 3]] → [1, 3]

The cables [2, 3], [1, 2] and [1, 3] form a loop. Any of them can go, but [1, 3] comes last in the list.

Example 2
cables=[[3, 1], [2, 4], [1, 4], [3, 4], [4, 5]] → [3, 4]

The loop is 3 – 1 – 4 – 3, and its last cable in the list is [3, 4]. Removing [4, 5] would cut computer 5 off.

Example 3
cables=[[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 1]] → [6, 1]
Constraints
  • n == len(cables)
  • 3 ≤ n ≤ 10⁴
  • 1 ≤ a, b ≤ n, a ≠ b
  • No two cables link the same pair of computers
  • All computers are connected into one network
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDo the Links Form a Tree MediumIsolated Groups in a Network MediumRatio Chain Queries MediumClusters of Linked Servers MediumSplit Into Two Teams Medium
loading Python…
Input
cables=[[2, 3], [1, 2], [3, 4], [1, 3]]
Expected
[1, 3]

Run checks the first 3 tests in your browser. Submit checks all 25 tests on the server, hidden ones included.