Monitoring~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceheaps
You work on a monitoring system. It records the latency of each request, in milliseconds, in the order the requests arrived. The on-call team watches a slow-tail signal: in each stretch of window requests in a row, the k-th slowest latency.
Your team lead asks: "Give me that number for every stretch." A log can hold 100,000 requests, and the window can hold thousands of them.
Write kth_slowest_per_window(latencies, window, k).
latencies[i] is the latency of request i.window requests in a row. There are len(latencies) - window + 1 of them, from the first to the last.k is a position counted from the slowest: k = 1 is the slowest request, k = 2 the second slowest, and so on. Requests with equal latency count as separate requests.k-th slowest latency.Input: latencies = [4, 1, 7, 3, 9, 2, 8], window = 3, k = 2
Output: [4, 3, 7, 3, 8]| Stretch | Latencies, slowest first | The 2nd slowest |
|---|---|---|
| 4, 1, 7 | 7, 4, 1 | 4 |
| 1, 7, 3 | 7, 3, 1 | 3 |
| 7, 3, 9 | 9, 7, 3 | 7 |
| 3, 9, 2 | 9, 3, 2 | 3 |
| 9, 2, 8 | 9, 8, 2 | 8 |
Input: latencies = [4, 1, 7, 3, 9, 2, 8], window = 3, k = 1
Output: [7, 7, 9, 9, 9]With k = 1 each answer is the slowest latency of the stretch.
Input: latencies = [5, 5, 5, 5], window = 2, k = 2
Output: [5, 5, 5]Equal latencies are different requests. In each stretch the second slowest request has latency 5.
1 ≤ len(latencies) ≤ 100,000, and each latency is from 0 to 1,000,000.1 ≤ window ≤ len(latencies)1 ≤ k ≤ windowSorting every stretch costs about window × log2(window) steps, and there are up to 100,000 stretches. With a window of 5,000 that is about 95,001 sorts of 5,000 numbers, which is far too slow. Moving from one stretch to the next only adds one request and removes one. A heap can follow that change in log2 n steps, but a heap cannot remove an item from its middle.