Search~50 min2s · 256 MBtarget O(n log n) time, O(n) spaceheaps
A search service records the response time of every request, in milliseconds. The on-call engineer watches the median response time of the last few seconds, because it is steadier than the average.
The service takes thousands of requests a second, so the median must be updated for each new request without sorting the window again.
Write window_medians(times, latencies, window).
i arrives at second times[i] and takes latencies[i] milliseconds. The times never go down.i arrives, the window holds every request j <= i with times[i] - times[j] < window. The request itself is in its window.Input: times = [1, 2, 4, 5, 9, 10], latencies = [30, 10, 50, 20, 40, 60], window = 5
Output: [30, 10, 30, 20, 20, 40]The trace sorts the latencies inside each window and takes the lower middle one.
| i | Time | Latencies in the window, sorted | Median (the lower one) |
|---|---|---|---|
| 0 | 1 | 30 | 30 |
| 1 | 2 | 10, 30 | 10 |
| 2 | 4 | 10, 30, 50 | 30 |
| 3 | 5 | 10, 20, 30, 50 | 20 |
| 4 | 9 | 20, 40 | 20 |
| 5 | 10 | 40, 60 | 40 |
At i = 3, all four requests are inside the window, and the lower middle of 10, 20, 30 and 50 is 20. At i = 4, the requests at times 1, 2 and 4 have left. The window holds 20 and 40, and its lower middle is 20.
Input: times = [3, 3, 3, 3], latencies = [8, 2, 6, 4], window = 1
Output: [8, 2, 6, 4]All four requests arrive in the same second. With window = 1, they all share the window. The medians are the lower middle values of 8, then 8 and 2, then 8, 2 and 6, then all four: [8, 2, 6, 4].
Input: times = [0, 10, 20], latencies = [70, 10, 40], window = 10
Output: [70, 10, 40]The window is 10 seconds. A request exactly 10 seconds old has left, so each window holds only the newest request, and the output is [70, 10, 40].
1 ≤ times.length ≤ 100,000; latencies has the same length0 ≤ times[i] ≤ 2,678,400 (seconds since the start of the month), never going down1 ≤ latencies[i] ≤ 1,000,000,000 (milliseconds)1 ≤ window ≤ 86,400 (seconds)Sorting the window for every request costs up to n × w log w, which is about 10^10 steps when a window holds thousands of requests. Two heaps split the window into a lower half and an upper half, so the median is always at the top of one of them. A request joins one heap in O(log n). A request that leaves is the problem, because a heap cannot remove an entry from its middle.