Engineering platform~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-261dfs
A data hall has n servers, numbered from 0, joined by network cables. A cable works in both directions. Two servers may be joined by more than one cable.
A network protocol needs the wiring to be a tree: every server reachable from every other, with exactly one path between any two. The team wants to remove exactly one cable to get a tree, and asks how many different cables would work.
Write count_removable_cables(n, cables).
cables[i] is [a, b]: a cable between servers a and b, with a different from b. The same pair may appear twice.n servers connected, with no loop.Input: n = 6, cables = [[0,1],[1,2],[2,3],[3,1],[3,4],[4,5]]
Output: 3There are 6 cables for 6 servers, so one loop is the only thing in the way. A depth-first walk from server 0 records the depth of each server and skips only the cable it arrived by.
| Step | Server | Cable read | What happens |
|---|---|---|---|
| 1 | 0 | to 1 | server 1 gets depth 1 |
| 2 | 1 | to 2 | server 2 gets depth 2 |
| 3 | 2 | to 3 | server 3 gets depth 3 |
| 4 | 3 | to 1 | server 1 is above, at depth 1: the loop has 3 - 1 + 1 = 3 cables |
| 5 | 3 | to 4, then 4 to 5 | servers 4 and 5 are reached: all 6 servers are connected |
The loop runs through servers 1, 2 and 3. Removing any of its 3 cables leaves a tree, so the answer is 3.
Input: n = 4, cables = [[0,1],[1,2],[2,3]]
Output: 0The wiring is already a tree. Removing a cable leaves two parts that are not connected.
Input: n = 3, cables = [[0,1],[0,1],[1,2]]
Output: 2Two cables join servers 0 and 1, so they form a loop of 2 cables. Removing either leaves a tree.
2 ≤ n ≤ 100,0000 ≤ cables.length ≤ 100,000, and each cable joins two different servers from 0 to n - 1Removing each cable and testing the rest costs about m × (n + m) = 100,000 × 200,000 = 2 × 10^10 steps. A tree on n servers has exactly n - 1 cables, so only a connected graph with n cables can work, and then exactly one loop exists. One walk finds that loop, and costs O(n).