Monitoring~12 min2s · 256 MBtarget O(n log n) time, O(n) spacetraversal · sorting
A monitoring system receives samples from a sensor. Each sample is a timestamp in seconds. Samples can arrive out of order, because the network delivers them at different speeds.
Your team lead says: "Tell me the longest silence: the largest gap between two samples that are neighbours in time."
A long silence may mean the sensor stopped for a while. You must find it from the list as it arrived.
Write largest_gap(samples).
samples[i] is the timestamp, in seconds, of one sample. The list is in arrival order, not time order.Input: samples = [40, 5, 12, 30, 7]
Output: 18In time order the samples are [5, 7, 12, 30, 40].
| Position | Sorted time | Gap to the previous sample |
|---|---|---|
| 0 | 5 | - |
| 1 | 7 | 2 |
| 2 | 12 | 5 |
| 3 | 30 | 18 |
| 4 | 40 | 10 |
The largest gap is 18.
Input: samples = [9]
Output: 0One sample has no neighbour.
Input: samples = [8, 8, 8]
Output: 0Samples at the same time have a gap of 0.
1 ≤ samples.length ≤ 100,000 (samples)0 ≤ samples[i] ≤ 1,000,000,000 (seconds)Comparing every sample with every other costs about n squared steps, 10,000,000,000 for 100,000 samples. Sorting costs about n log n, which is a few million steps.