Monitoring~30 min2s · 256 MBtarget O(n + m log m) time, O(n + m) spacecycle-detection
An observability tool studies which services call which. There are n services, numbered from 0. A call goes from one service to another, and a service may call itself.
The tool replays the calls with a fixed walk. It takes the services in order 0, 1, 2 and so on, and skips a service that an earlier walk already covered. From a service, it follows the calls in ascending order of the service called, going into a new service at once. A call that leads back to a service whose own calls are still being followed is reentrant.
Write count_reentrant_calls(n, calls).
calls[i] is [a, b]: service a calls service b. The same call may be listed more than once, and each listing counts as a call.Input: n = 6, calls = [[0,1],[1,2],[2,0],[2,3],[3,1],[4,5],[5,5],[0,2]]
Output: 3Each service has a colour: white if the walk has not reached it, grey while it is in progress, and black when it is finished. A call to a grey service is reentrant.
| Step | Service | Call followed | Colour of the target | Result |
|---|---|---|---|---|
| 1 | 0 | 0 to 1 | white | enter 1 |
| 2 | 1 | 1 to 2 | white | enter 2 |
| 3 | 2 | 2 to 0 | grey | reentrant, count 1 |
| 4 | 2 | 2 to 3 | white | enter 3 |
| 5 | 3 | 3 to 1 | grey | reentrant, count 2 |
| 6 | 0 | 0 to 2, later | black | not reentrant |
| 7 | 5 | 5 to 5 | grey | reentrant, count 3 |
Services 3, 2 and 1 finish, and then service 0 follows its last call, to the finished service 2. The walk then starts again at service 4.
Input: n = 3, calls = []
Output: 0No service calls another.
Input: n = 2, calls = [[0,0],[0,0]]
Output: 2Service 0 calls itself twice, and each call is reentrant.
1 ≤ n ≤ 100,0000 ≤ calls.length ≤ 200,000, and each call is [a, b] with 0 ≤ a, b < nA walk that keeps the services in progress and the finished services in two plain lists searches them for every call. With 200,000 calls and 100,000 services that is about 2 × 10^10 steps. Three colours in an array make each test O(1), so the whole walk costs O(n + m) after sorting the calls, about 3 × 10^6 steps.