Music streaming app~40 min2s · 256 MBtarget O(n + m) time, O(n + m) spacedfs · traversal
A video platform relays a live stream from an origin relay s to an edge relay t over two-way links between relays. Two relays may share more than one link, and a link never joins a relay to itself.
A link is critical for this stream when its failure leaves no route at all from s to t. The operators want to know how many links are critical. If the stream cannot reach t even when every link works, they want to know that instead.
Write separating_links(n, links, s, t).
n relays, numbered from 0 to n - 1.links[i] is [a, b]: a two-way link between relays a and b. The same pair may appear more than once, and a differs from b.s to t.s to t. If s equals t, that number is 0.Input: n = 9, links = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,5],[5,3],[5,6],[6,7],[1,8]], s = 0, t = 7
Output: 3Relays 0, 1 and 2 form a ring, and so do relays 3, 4 and 5. A single link joins relay 2 to relay 3. Relays 6 and 7 form a tail off relay 5, and relay 8 hangs off relay 1.
The links 2-3, 5-6 and 6-7 are on every route from 0 to 7. The link 1-8 is a dead end.
The solution walks from the origin and records a visit time tin and a low time low for each relay. A tree link from a parent to a child is a bridge when low[child] is above tin[parent]. Only the links on the walk's path from s to t can separate them.
| Relay | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| tin | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| low | 0 | 0 | 0 | 3 | 3 | 3 | 6 | 7 | 8 |
Climb from relay 7 to relay 0. The steps with low[child] > tin[parent] are 7 to 6 (7 > 6), 6 to 5 (6 > 5) and 3 to 2 (3 > 2). That makes three.
Input: n = 3, links = [[0,1],[0,1],[1,2]], s = 0, t = 2
Output: 1Relays 0 and 1 share two links, so neither is critical. Only the link 1-2 is.
Input: n = 4, links = [[0,1],[2,3]], s = 0, t = 3
Output: -1Relay 3 is in a different group of relays, so there is no route.
1 ≤ n ≤ 100,0000 ≤ links.length ≤ 100,000, and each link is [a, b] with 0 ≤ a, b < n and a ≠ b0 ≤ s, t < nRemoving each link and searching again costs m × (n + m), about 2 × 10^10 steps for the largest input. One depth-first walk from the origin costs about 4 × 10^5 steps, and the climb from the edge relay costs at most n more.