Ride-hailing app~25 min2s · 256 MBtarget O(q log q) time, O(q) spaceclassic twin: lc-981binary-search
A ride-hailing app stores a price multiplier for each zone of a city, as a whole number of hundredths. The multiplier is set by a time, and the app keeps every earlier value.
Support staff and billing check what a zone's multiplier was at a given time. The answer is the latest value that was set at or before that time, or -1 if the zone had no value yet.
Write values_at_times(ops). Each row of ops is one operation, in the order it is received.
[0, key, value, time] stores value for the zone key from time.[1, key, time, 0] asks for the value of key at time: the value with the latest time that is at most time, or -1 if there is none.Input: ops = [[0, 1, 120, 10], [0, 1, 150, 20], [0, 2, 100, 15], [1, 1, 12, 0], [1, 1, 20, 0], [1, 1, 25, 0], [1, 2, 14, 0], [1, 2, 15, 0], [1, 3, 40, 0], [0, 1, 90, 30], [1, 1, 29, 0], [1, 1, 30, 0]]
Output: [120, 150, 150, -1, 100, -1, 150, 90]For the zone 1, the stored times are 10, 20 and later 30. Take the question [1, 1, 12, 0], asked when the zone has two sets, at times [10, 20]. The window [lo, hi) holds the sets in question, and the check is "this set's time is at most 12".
| Step | lo | hi | mid | Time of set | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 2 | 1 | 20 | 20 > 12, so hi = 1 |
| 2 | 0 | 1 | 0 | 10 | 10 ≤ 12, so lo = 1 |
| end | 1 | 1 | the last set at or before time 12 is set 0, with value 120 |
The question [1, 1, 25, 0] gives 150, and [1, 2, 14, 0] gives -1, because the zone 2 was first set at time 15.
Input: ops = [[1, 4, 10, 0], [0, 4, 7, 10], [1, 4, 9, 0], [1, 4, 10, 0]]
Output: [-1, -1, 7]A set at time 10 counts for a question at time 10, but not for time 9.
Input: ops = [[0, 0, 5, 1], [0, 0, 6, 2], [0, 0, 7, 3], [1, 0, 100, 0], [1, 0, 0, 0]]
Output: [7, -1]A question after the last set returns the last value.
0 ≤ ops.length ≤ 100,000, and every row has 4 numbers0 ≤ key ≤ 99,999, 0 ≤ value ≤ 1,000,000, and 0 ≤ time ≤ 1,000,000,000Scanning every set of a zone for each question costs up to 10^5 steps a question, so about 5 × 10^9 steps for 5 × 10^4 questions. The sets of one zone arrive in time order, so a binary search over its times costs about 17 steps.