Engineering platform~40 min2s · 256 MBtarget O(n + m) time, O(n + m) spacedfs · traversal
A platform team keeps a map of which internal services call which. A call from service a to service b goes one way. A service never calls itself, but the same call may be listed twice.
When one service in a loop of calls fails, the whole loop can stall, so the team restarts such services together. Two services are in the same restart group when each can reach the other through calls, directly or through other services. Every service is in exactly one group.
Write restart_groups(n, calls).
n services, numbered from 0 to n - 1.calls[i] is [a, b]: service a calls service b.n. Entry v is the smallest service id in the restart group of service v.Input: n = 7, calls = [[0,1],[1,2],[2,0],[2,3],[3,4],[4,5],[5,3],[6,5]]
Output: [0, 0, 0, 3, 3, 3, 6]Services 0, 1 and 2 call each other in a ring, and so do 3, 4 and 5. Service 2 calls service 3, but nothing in the second ring calls back. Service 6 calls into the second ring and nobody calls it.
The solution walks the calls depth first and notes the order in which each service finishes. It then walks the reversed calls, starting with the service that finished last. Each walk in the second pass collects one group.
| Pass | Start | What the walk reaches | Group |
|---|---|---|---|
| 1 | 0 | goes 0, 1, 2, 3, 4, 5 and finishes 5, 4, 3, 2, 1, 0 | finishing order so far: 5, 4, 3, 2, 1, 0 |
| 1 | 6 | calls 5, which is seen, so 6 finishes | finishing order: 5, 4, 3, 2, 1, 0, 6 |
| 2 | 6 | nobody calls 6 | {6}, label 6 |
| 2 | 0 | callers of 0: 2, then callers of 2: 1 | {0, 1, 2}, label 0 |
| 2 | 3 | callers of 3: 2 (taken) and 5, then callers of 5: 4 and 6 (taken) | {3, 4, 5}, label 3 |
Input: n = 3, calls = [[0,1],[1,2]]
Output: [0, 1, 2]Service 0 reaches 1 and 2, but nothing reaches back. Every service is its own group.
Input: n = 4, calls = [[0,1],[1,2],[2,3],[3,0]]
Output: [0, 0, 0, 0]One ring holds all four services, so they restart together.
1 ≤ n ≤ 100,0000 ≤ calls.length ≤ 100,000, and each call is [a, b] with 0 ≤ a, b < n and a ≠ bAsking, for every pair of services, whether each reaches the other is about n² pairs, which is 10^10 for 100,000 services. Even one search from each service costs n × (n + m), about 2 × 10^10 steps. Two depth-first passes visit each service and each call twice, about 6 × 10^5 steps.