Monitoring~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-295heaps
A monitoring system records the response time of each request to a service, in microseconds. A dashboard shows the median response time of everything seen so far, updated after every request. The median is steady when a few requests are very slow, so teams prefer it to the average.
A service can see 300,000 requests in a window, and a timeout can reach 30 minutes, which is 1.8 × 10^9 microseconds. Re-sorting after each request would be too slow.
Write running_medians(latencies).
latencies[i] is the response time of the i-th request.m requests, sort their times. If m is odd, the median is the middle time. If m is even, the median is the average of the two middle times, rounded down to a whole number.n whole numbers.Input: latencies = [5, 15, 1, 3]
Output: [5, 10, 5, 4]Keep the lower half in a max-heap and the upper half in a min-heap. The lower half holds the same number of values as the upper half, or one more. For an odd count the median is the lower top, and for an even count it is the average of the two tops.
| Value | Goes to | Lower half | Upper half | Median |
|---|---|---|---|---|
| 5 | lower (it is empty) | 5 | 5 | |
| 15 | upper (15 > 5) | 5 | 15 | (5 + 15) / 2 = 10 |
| 1 | lower (1 ≤ 5) | 1, 5 | 15 | 5 |
| 3 | lower (3 ≤ 5), then 5 moves up | 1, 3 | 5, 15 | (3 + 5) / 2 = 4 |
Input: latencies = [2000000000, 2000000000]
Output: [2000000000, 2000000000]The two values add up to 4 × 10^9, which is larger than the largest int, 2,147,483,647. The median is still 2,000,000,000.
Input: latencies = [1, 2]
Output: [1, 1]After two values the average of 1 and 2 is 1.5, and rounded down it is 1.
1 ≤ length of latencies ≤ 3 × 10^50 ≤ latencies[i] ≤ 2 × 10^9Two values can add up to 4 × 10^9, which does not fit in a 32-bit int (the largest is about 2.147 × 10^9). Java and C++ need 64-bit arithmetic for the sum, or a form such as low + (high - low) / 2.
The length, 300,000, rules out two things. Sorting after every value costs about n^2 log n, and inserting into a sorted array moves up to n values for each new one.