Monitoring~15 min2s · 256 MBtarget O(n) time, O(1) spacetraversal
A monitoring system records the latency of a service once per second. A single slow request can make one reading jump far above its neighbours, and a chart drawn from raw readings looks noisy.
The chart smooths the readings with a median of three. For each group of three neighbouring readings it keeps the middle value when they are put in order, so one spike never reaches the chart.
Three weeks of readings hold 1,814,400 numbers, and the chart may cover a few days more.
Write window_medians(readings).
readings[i] is the latency reading at second i.readings[i], readings[i + 1] and readings[i + 2].Input: readings = [5, 1, 9, 3, 7, 2]
Output: [5, 3, 7, 3]There are 6 readings, so there are 4 windows.
| Start | Window | Median |
|---|---|---|
| 0 | [5, 1, 9] | 5 |
| 1 | [1, 9, 3] | 3 |
| 2 | [9, 3, 7] | 7 |
| 3 | [3, 7, 2] | 3 |
Input: readings = [4, 4, 4]
Output: [4]Equal readings give the same value.
Input: readings = [8, 3]
Output: []Two readings hold no window of three.
0 ≤ readings.length ≤ 2,000,000 (seconds in the record)1 ≤ readings[i] ≤ 1,000,000,000 (latency in microseconds)There are 1,999,998 windows. Whatever the method, every reading must be read, so about two million steps is the floor.
Copying and sorting each window costs 11,999,988 comparisons. Placing the third reading against an ordered pair needs at most 3 comparisons per window and no list, at most 5,999,994 in all. The gain is a constant factor.