One Cable Too Many

Mediumunion-findAlso known as Redundant Connection

A small office network has n devices, numbered 0 to n - 1. It used to be wired as a tree: every device reachable from every other, with no loops. Then someone plugged in one extra cable, and now packets circle round a loop and the switches complain.

The installer's log lists every cable in the order it was plugged in. You need to pick one cable to unplug so the network is a tree again. Several cables on the loop would work; the installer asks for the one that went in latest.

Your task

Write cableToUnplug(n, cables). cables has exactly n entries, each [a, b] joining devices a and b. It is a tree on all n devices plus one extra cable.

Return the cable whose removal leaves a tree. If several cables qualify, return the one that appears last in cables. Return it exactly as written in the list.

cableToUnplug(n: int, cables: int[][]) → int[]

Examples

Example 1
Input
n = 4
cables = [[0, 1], [1, 2], [2, 0], [2, 3]]
Output
[2, 0]
Why

The loop is 0-1-2-0. Unplugging any of its three cables leaves a tree. Of those, [2, 0] is the latest in the log. [2, 3] comes later, but it is not on the loop: unplugging it would cut device 3 off.

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

The loop is 1-2-3-4-1, made of [1, 2], [3, 4], [2, 3] and [4, 1]. The latest of those is [4, 1].

Constraints

  • 3 ≤ n ≤ 1,000
  • cables.length = n
  • 0 ≤ a, b < n, a ≠ b, and no two cables join the same pair of devices
  • Removing some cable leaves every device connected with no loop
Start with brute force

Try removing each cable, starting from the end of the log, and check whether the rest is still connected, for example with a depth-first search. Return the first one that works.

Each check walks the whole network, so this costs O(n²). With 1,000 devices that is around a million steps: fine here, but it does the same connectivity work over and over. Union-find gets the answer in one pass.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code