Monitoring~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1123tree-recursion
A monitoring system stores a trace as a tree of calls. Each call has up to two calls that it makes, and call 0 is the entry point.
When a trace is slow, the engineer starts at the deepest calls. The system should name the smallest call that contains every one of the deepest calls, so the engineer opens one place.
A trace can hold 100,000 calls and can be a chain.
Write smallest_call_over_deepest(left, right).
0 to n - 1, and call 0 is the entry point.left[i] and right[i] are the calls made by call i, or -1 where there is none.0. The deepest calls are those with the largest depth.Input: left = [1, 3, -1, -1, 5, -1, -1], right = [2, 4, -1, -1, 6, -1, -1]
Output: 4The deepest calls are 5 and 6, at depth 3. Both are made by call 4, and no lower call holds both. The walk goes backwards through the list of calls.
| Round | Call | Depth | Deepest calls in its side | What happens |
|---|---|---|---|---|
| 1 | 3 | 2 | 0 | adds 0 to node 1 |
| 2 | 5 | 3 | 1 | adds 1 to node 4 |
| 3 | 6 | 3 | 1 | adds 1 to node 4 |
| 4 | 4 | 2 | 2 | stop: answer |
There are 2 deepest calls, so the first call whose side holds 2 is the answer.
Input: left = [-1], right = [-1]
Output: 0One call: it is the deepest call and holds itself.
Input: left = [1, 2, -1], right = [-1, -1, -1]
Output: 2A chain with one deepest call: it holds itself.
1 ≤ length of left = length of right ≤ 10^5left and right is -1 or a call number from 1 to n - 10A trace can be a chain of 100,000 calls, so a recursive walk can be 100,000 calls deep. Walking the whole subtree of every call to count the deepest ones costs about n^2 / 2 steps on a chain, or 5 x 10^9.
Find the deepest level once. Then pass counts up from the calls to their parents, each call once.