Engineering platform~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1448dfs · tree-recursion
A platform app traces how one request travels through its services. Service 0 receives the request and calls at most two other services, a left one and a right one. Each of those calls at most two more, so the calls form a tree.
Every service has a latency in milliseconds. A service is a bottleneck when no service above it on its call path is slower. The call path runs from service 0 down to the service. Your team lead asks: how many services are bottlenecks?
Write count_bottlenecks(latency, left, right).
0 to n - 1, and service 0 receives the request. There is at least one service.latency[i] is the latency of service i. left[i] and right[i] are the services that service i calls, or -1 where there is none.i is a bottleneck when latency[i] is at least the latency of every service above it on its call path. Equal latencies count.0 has nothing above it, so it is always a bottleneck.Input: latency = [5, 3, 8, 3, 6, 9, 2], left = [1, 3, 5, -1, -1, -1, -1], right = [2, 4, 6, -1, -1, -1, -1]
Output: 4Service 0 calls 1 and 2. Service 1 calls 3 and 4. Service 2 calls 5 and 6.
Walk down from service 0 and carry the highest latency seen above each service. A service counts when its latency is at least that number.
| Service | Highest latency above | Latency | Bottleneck? |
|---|---|---|---|
0 |
none | 5 | yes |
1 |
5 | 3 | no |
2 |
5 | 8 | yes |
3 |
5 | 3 | no |
4 |
5 | 6 | yes |
5 |
8 | 9 | yes |
6 |
8 | 2 | no |
Input: latency = [7, 7, 7], left = [1, -1, -1], right = [2, -1, -1]
Output: 3The latencies are equal, and equal counts. All three services are bottlenecks.
Input: latency = [9, 4, 1, 6], left = [1, 2, 3, -1], right = [-1, -1, -1, -1]
Output: 1The calls form one path. Every service after service 0 is faster than service 0, so only service 0 counts.
1 ≤ n ≤ 100000, where n is the number of services0 ≤ latency[i] ≤ 1000000left[i] and right[i] are -1 or a service number from 0 to n - 10: every other service is called by exactly one serviceA tree of 100,000 services can be one long path, with 100,000 services on it. Climbing from every service to the top costs about 100,000 × 100,000 ÷ 2 steps, which is 5 × 10^9. That is far too slow.
A path that long also breaks a recursive walk. Many languages stop at a few thousand nested calls. Use your own stack, and visit each service once.