Monitoring~35 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-1192dfs · traversal
A monitoring system pings services over two-way health-check links. Services are numbered from 0. Two services may share more than one link, and a link never joins a service to itself.
If a link fails, some services may become unreachable from others. A link is fragile when its failure splits a group of connected services into two groups. You want a list of all fragile links.
Write fragile_links(n, links).
n services, numbered from 0 to n - 1.links[i] is [a, b]: a two-way link between services a and b. The same pair may appear more than once, and a differs from b.[a, b] with a < b. Sort the list by a, then by b.Input: n = 7, links = [[0,1],[1,2],[2,0],[1,3],[3,4],[4,5],[5,3],[5,6]]
Output: [[1, 3], [5, 6]]Services 0, 1 and 2 form a cycle, and so do services 3, 4 and 5. The link between 1 and 3 is the only way between the two cycles. Service 6 hangs off service 5 by one link.
The solution walks depth first from service 0 and records a discovery time for each service. It also records the lowest discovery time reachable from the service and its subtree by using one extra link.
| Service | Discovery time | Lowest time reached |
|---|---|---|
| 0 | 0 | 0 |
| 1 | 1 | 0 |
| 2 | 2 | 0 |
| 3 | 3 | 3 |
| 4 | 4 | 3 |
| 5 | 5 | 3 |
| 6 | 6 | 6 |
The link from service 1 to its child 3 is fragile when low[3] > disc[1]. Here low[3] is 3 and disc[1] is 1. Likewise low[6] is 6 and disc[5] is 5, so the link from 5 to 6 is fragile. Every other child can reach back to its parent or higher.
Input: n = 3, links = [[0,1],[0,1],[1,2]]
Output: [[1, 2]]There are two links between services 0 and 1. If one fails, the other keeps them connected, so neither is fragile. The link between 1 and 2 is the only one.
Input: n = 2, links = [[0,1]]
Output: [[0, 1]]The single link is the only connection, so it is fragile.
1 ≤ n ≤ 100,0000 ≤ links.length ≤ 200,000, and each link is [a, b] with 0 ≤ a, b < n and a ≠ bRemoving each link and searching the rest costs about m × (n + m) steps. For 200,000 links and 100,000 services that is more than 5 × 10^10. One depth-first walk with discovery times visits each service and link once, about 3 × 10^5 steps.