Monitoring~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-515bfs
A monitoring system records one request as a call tree. Each call makes at most two calls of its own, a left one and a right one. Every call has a number: how many milliseconds it was slower than its usual time. A negative number means it was faster.
Your team lead wants one number for each depth of the tree: the slowdown of the slowest call at that depth. Depth 1 is the first call, depth 2 holds the calls it made, and so on.
Write slowest_call_per_depth(values, left, right).
0 to n - 1, and call 0 is the first call. An empty trace has three empty lists.values[i] is the slowdown of call i. left[i] and right[i] are the numbers of the calls it makes, or -1 where there is none.Input: values = [8, 3, 10, 1, 6, 14, 4, 7, 13], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1]
Output: [8, 10, 14, 13]Call 0 (slowdown 8) makes 1 (3) and 2 (10). Call 1 makes 3 (1) and 4 (6). Call 2 makes only a right call 5 (14).
Call 4 makes 6 (4) and 7 (7). Call 5 makes only a left call 8 (13).
Keep a queue of the calls waiting. A new maximum starts for every round.
| Round | Queue at the start (slowdowns) | Calls at the depth | Largest | Queue at the end |
|---|---|---|---|---|
| 1 | 8 | 1 | 8 | 3, 10 |
| 2 | 3, 10 | 2 | 10 | 1, 6, 14 |
| 3 | 1, 6, 14 | 3 | 14 | 4, 7, 13 |
| 4 | 4, 7, 13 | 3 | 13 | empty |
Input: values = [-5, -2, -9], left = [1, 2, -1], right = [-1, -1, -1]
Output: [-5, -2, -9]A chain of faster-than-usual calls. Each depth has one call, so each largest is that call.
Input: values = [], left = [], right = []
Output: []0 ≤ length of values = length of left = length of right ≤ 10^5-10^6 ≤ values[i] ≤ 10^6left and right is -1 or a call number from 1 to n - 10A trace can be one chain of 100,000 calls, which has 100,000 depths. Scanning every call for every depth costs about n^2 steps on it.
Build each depth from the depth above it, and look at every call once.