One Cable Too Many

Mediumunion-findAlso known as Redundant Connection

An office network has n devices, numbered 0 to n - 1. It was wired as a tree, which means every device can reach every other device and there are no loops. Then someone plugged in one extra cable, and now packets can circle around a loop.

The installer's log lists every cable in the order it went in. You must unplug one cable so that the network is a tree again. Any cable on the loop would work, and the installer wants the one that was plugged 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, and unplugging any of its three cables leaves a tree. [2, 0] is the latest of them. The cable [2, 3] comes later in the log but is not on the loop, and 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 with a depth-first search whether the rest is still connected. Return the first one that works.

Each check walks the whole network, so this takes O(n²) time, around a million steps for 1,000 devices. That is acceptable for these limits, but it repeats the same connectivity work for every cable, while union-find needs only 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