Maps app~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceheaps
You work on a maps app. Each road segment has a travel-time estimate in seconds, and the estimate changes whenever a new measurement arrives for that segment. The app shows one city-wide figure: the median of the latest estimates of all segments that have an estimate.
Your team lead asks: "What is the city-wide figure after each measurement?" The log holds up to 200,000 measurements, and up to 100,000 different segments.
Write median_of_latest(events).
events[i] = [segment, seconds] is the measurement i: the new estimate of road segment segment. It replaces the earlier estimate of that segment, if there is one.i, take the latest estimate of each segment that has appeared so far.(m + 1) / 2, rounded down, counting from 1, where m is their number. With m = 4 it is the 2nd, and with m = 5 it is the 3rd.Input: events = [[3, 40], [7, 10], [3, 20], [9, 30], [7, 50], [9, 30], [5, 5]]
Output: [40, 10, 10, 20, 30, 30, 20]| After event | Latest estimates (segment: seconds) | Sorted | Figure |
|---|---|---|---|
| 1 | 3: 40 | 40 | 40 |
| 2 | 3: 40, 7: 10 | 10, 40 | 10 |
| 3 | 3: 20, 7: 10 | 10, 20 | 10 |
| 4 | 3: 20, 7: 10, 9: 30 | 10, 20, 30 | 20 |
| 5 | 3: 20, 7: 50, 9: 30 | 20, 30, 50 | 30 |
| 6 | the same estimate for segment 9 | 20, 30, 50 | 30 |
| 7 | 3: 20, 7: 50, 9: 30, 5: 5 | 5, 20, 30, 50 | 20 |
Input: events = [[1, 8]]
Output: [8]Input: events = [[2, 5], [2, 9], [2, 1]]
Output: [5, 9, 1]One segment only: its latest estimate is the median.
1 ≤ events.length ≤ 200,000 (measurements)0 ≤ segment ≤ 1,000,000, and up to 100,000 different segments appear0 ≤ seconds ≤ 1,000,000Sorting the latest estimates after each measurement costs up to 100,000 × 17 steps. For 200,000 measurements that is about 340,000,000,000 steps.
Two heaps hold the lower and the upper half, and the median is on top of one of them. A new measurement removes one old value and adds one new value, and each costs about 17 steps.