Chat app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-1740tree-recursion
A chat app shows an org chart. Each person has up to two direct reports, and person 0 is at the top.
Before two people open a group chat, the app shows how far apart they are in the chart: the number of links on the path between them. A link joins a manager and a direct report.
The chart can hold 100,000 people and can be a chain. Your team lead wants the count without trying every path.
Write distance_between(left, right, a, b).
0 to n - 1, and person 0 is the top. There is at least one person.left[i] and right[i] are the direct reports of person i, or -1 where there is none. Every person except 0 has exactly one manager.a and b are people. They can be the same person.a and b. The path may go up to a manager and down again.Input: left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], a = 6, b = 8
Output: 6The path goes up from person 6 to person 0 and down to person 8. The lowest common manager is the top, 3 links above each.
| Stage | a | b | Links counted |
|---|---|---|---|
| start (depths 3 and 3) | 6 | 8 | 0 |
| lift both | 4 | 5 | 2 |
| lift both | 1 | 2 | 4 |
| lift both | 0 | 0 | 6 |
The two people meet at person 0 after 3 rounds of lifting both, which is 6 links.
Input: left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], a = 4, b = 4
Output: 0The same person twice.
Input: left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], a = 1, b = 7
Output: 2Person 1 is the manager of the manager of person 7.
1 ≤ length of left = length of right ≤ 10^5left and right is -1 or a person number from 1 to n - 100 ≤ a, b ≤ n - 1The chart can be a chain of 100,000 people, so a path can have 99,999 links and a recursive walk can be 100,000 calls deep. Trying every path from a costs a walk each.
Walk the chart once to record each person's manager and depth. Then lift the two people towards the top: no more than n steps.