Skip to the code
cf.
+25 XP

#455 Extra Cable in the Office Network

medium

An office network of n devices, numbered 0 to n - 1, was meant to be a tree: connected, with no loops. Someone added one extra cable, so cables now has n entries and contains exactly one loop. Each cable [a, b] works both ways.

Write extraCable(n, cables) that returns a cable that can be removed so the rest is a tree again. If several cables would work, return the one that appears last in cables.

Example 1

Input: n = 3, cables = [[0,1],[0,2],[1,2]]
Output: [1,2]

All three cables form the loop, and [1, 2] comes last.

Example 2

Input: n = 5, cables = [[0,1],[1,2],[2,3],[1,3],[0,4]]
Output: [1,3]

The loop is 1-2-3. Of its cables, [1, 3] appears last.

Constraints

  • 3 <= n <= 10000
  • cables.length === n
  • No cable is listed twice and none connects a device to itself.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).