Ride-hailing app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-236tree-recursion
A ride-hailing app has an escalation chart for its support agents. Each agent has up to two direct reports, and agent 0 is at the top.
When two agents disagree on a case, the app asks the lowest manager who is above both of them. If one of the two agents manages the other, that agent decides.
The chart can hold 100,000 agents and can be a chain. The agent ids carry no order, so the ids cannot tell you which side to take.
Write lowest_common_manager(values, left, right, p, q).
0 to n - 1, and agent 0 is the top. There are at least two agents.values[i] is the id of agent i, and the ids are distinct. left[i] and right[i] are the direct reports of agent i, or -1 where there is none.p and q are the ids of two different agents.Input: values = [31, 12, 47, 5, 28, 60, 19, 36, 8], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], p = 19, q = 36
Output: 28Agents with ids 19 and 36 are the two reports of the agent with id 28. Going backwards through the list of agents, the first agent whose side holds both is 28.
| Round | Agent (id) | Count when reached | What happens |
|---|---|---|---|
| 1 | 3 (5) | 0 | adds 0 to node 1 |
| 2 | 6 (19) | 1 | adds 1 to node 4 |
| 3 | 7 (36) | 1 | adds 1 to node 4 |
| 4 | 4 (28) | 2 | stop: answer |
The agent list from the top is [0, 2, 5, 8, 1, 4, 7, 6, 3], so the walk back reads the last agents first.
Input: values = [31, 12, 47, 5, 28, 60, 19, 36, 8], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], p = 19, q = 47
Output: 31The two agents are on different sides of the top.
Input: values = [31, 12, 47, 5, 28, 60, 19, 36, 8], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], p = 12, q = 19
Output: 12The agent with id 12 manages the agent with id 19, so it is the answer.
2 ≤ length of values = length of left = length of right ≤ 10^51 ≤ values[i] ≤ 10^6, and the ids are distinct and in no orderleft and right is -1 or an agent number from 1 to n - 10p and q are different ids that appear in valuesThe chart can be a chain of 100,000 agents, so a recursive walk can be 100,000 calls deep. Lists of whole routes with lookups cost about n^2 / 2 steps on a chain, or 5 x 10^9.
List the agents once so that every manager comes before the agents under them, then go through the list backwards and add up counts. Each agent is handled once.