Maps app~15 min2s · 256 MBtarget O(h) time, O(1) spaceclassic twin: lc-235tree-recursion
A maps app divides a city into delivery zones. The zone ids are kept in a search tree: smaller ids on the left, larger ids on the right, and zone 0 at the top.
Support wants to put two zones under one courier. For that, it needs the lowest zone that lies on the path from the top to both of them.
The tree can hold 100,000 zones, and it can be a chain. Your team lead wants the answer from one walk down from the top.
Write lowest_shared_zone(values, left, right, p, q).
0 to n - 1, and zone 0 is the top of the tree. There are at least two zones.values[i] is the id of zone i. left[i] and right[i] are the zones on its left and right, or -1 where there is none.p and q are the ids of two different zones in the tree. A zone counts as lying on its own path.p and on the path from the top to q.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], p = 4, q = 7
Output: 6The zones with ids 4 and 7 are both under 6, and they go to different sides of it, so 6 is the lowest zone that covers both.
| Round | Zone (id) | Both ids smaller? | Both ids larger? | Move |
|---|---|---|---|---|
| 1 | 0 (8) | yes | no | left |
| 2 | 1 (3) | no | yes | right |
| 3 | 4 (6) | no | no | stop: answer |
The walk reads 3 zones. It never looks at the right side of the top.
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], p = 1, q = 13
Output: 8Input: 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], p = 3, q = 7
Output: 3The zone with id 3 is on the path to 7, 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 distinctleft and right is -1 or a zone number from 1 to n - 10p and q are different ids that appear in valuesA chain of 100,000 zones is possible, so the walk can be 100,000 steps long and a recursive walk can be 100,000 calls deep. One loop from the top reads each zone at most once.
A search that builds the whole path of each zone as a list and then looks zones up in it scans the list for each lookup. On a chain that is about n^2 / 2 steps, or 5 x 10^9.