Ride-hailing app~15 min2s · 256 MBtarget O(h + k) time, O(h) spaceclassic twin: lc-938tree-recursion
A ride-hailing app issues trip ids in increasing order and keeps them in a search tree. Every night a check adds up the ids in one range, for example every id from 5 to 13, and compares the total with a counter.
The app can hold 100,000 ids. Your team lead wants the check to skip every part of the tree that cannot hold an id in the range.
Write range_total(values, left, right, low, high).
0 to n - 1, and trip 0 is the top of the tree. An empty tree has three empty lists.values[i] is the id of trip i. left[i] and right[i] are the trips on its left and right, or -1 where there is none.low to high, both ends included. Return 0 for an empty tree and when no id is in the range. The total can pass 2 x 10^9, so it needs a 64-bit integer.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], low = 5, high = 13
Output: 44The ids from 5 to 13 are 6, 7, 8, 10 and 13, so the total is 44. The stack walk looks at 8 of the 9 trips.
The id 3 is below 5, so everything on its left is below 5 too, and its left side is skipped. The id 14 is above 13, so it adds nothing and its right side would not be looked at.
| Node taken (id) | In the range? | Look at the left side? | Look at the right side? | Total so far |
|---|---|---|---|---|
| 8 | yes | yes | yes | 8 |
| 10 | yes | no | yes | 18 |
| 14 | no | yes | no | 18 |
| 13 | yes | no | no | 31 |
| 3 | no | no | yes | 31 |
| 6 | yes | yes | yes | 37 |
| 7 | yes | no | no | 44 |
| 4 | no | no | no | 44 |
Input: values = [7], left = [-1], right = [-1], low = 7, high = 7
Output: 7Input: values = [], left = [], right = [], low = 3, high = 9
Output: 00 ≤ length of values = length of left = length of right ≤ 10^51 ≤ values[i] ≤ 10^9, and the ids are distinctleft and right is -1 or a trip number from 1 to n - 101 ≤ low ≤ high ≤ 10^9Ids can be a chain of 100,000 trips, because ids may arrive in sorted order. A height-based cost is then no better than n.
Even so, an answer that never looks at a side that cannot hold an id in the range does the least work possible. It needs about the height of the tree plus the number of ids it adds.