Monitoring~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceheaps
A monitoring system watches a web service. After every request, the dashboard shows the 90th percentile latency: the response time that 90 percent of the requests so far did not exceed. Teams use it because a few very slow requests do not move it much, as they move the maximum.
A service handles up to 300,000 requests in a window, and the dashboard must update after each one. Sorting all the latencies after every request would be too slow.
Write p90_after_each(latencies).
latencies[i] is the response time of the i-th request, in milliseconds.m requests, sort their latencies from the smallest. The 90th percentile is the value at rank (9m + 9) // 10 in that list, where the smallest value has rank 1. This is the smallest rank that covers at least 90 percent of m.n numbers.Input: latencies = [120, 80, 300, 95, 110, 70, 250, 90, 85, 60]
Output: [120, 120, 300, 300, 300, 300, 300, 300, 300, 250]The rank is (9m + 9) // 10. For m from 1 to 9 it equals m, so the answer is the largest latency so far. At m = 10 the rank is 9, so the largest latency is left out.
Keep the rank smallest latencies in a max-heap, and the rest in a min-heap. The top of the max-heap is the answer.
| Request | Latency | Rank | The rank smallest, in order |
Answer |
|---|---|---|---|---|
| 1 | 120 | 1 | 120 | 120 |
| 2 | 80 | 2 | 80, 120 | 120 |
| 3 | 300 | 3 | 80, 120, 300 | 300 |
| 8 | 90 | 8 | 70, 80, 90, 95, 110, 120, 250, 300 | 300 |
| 9 | 85 | 9 | 70, 80, 85, 90, 95, 110, 120, 250, 300 | 300 |
| 10 | 60 | 9 | 60, 70, 80, 85, 90, 95, 110, 120, 250 (300 moves to the upper part) | 250 |
Requests 4 to 7 follow the same pattern as request 3: nothing is left in the upper part, so the answer is the largest latency.
Input: latencies = [50]
Output: [50]One request: its latency is the 90th percentile.
Input: latencies = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
Output: [10, 20, 30, 40, 50, 60, 70, 80, 90, 90, 100]The rank stays at 9 for the 10th request, so the answer stays 90. It grows to 10 at the 11th, and the answer becomes 100.
1 ≤ length of latencies ≤ 3 × 10^50 ≤ latencies[i] ≤ 10^9Sorting each prefix costs about n^2 log n steps, which is more than 10^12 for 300,000 requests. A sorted array with binary insertion also finds the place in log n steps, but each insert moves up to n values. A heap handles one new latency in about log n steps.
The rank grows by 0 or 1 at each request, so at most one latency moves across the cut each time.