Monitoring~25 min2s · 256 MBtarget O(q log n) time, O(1) spaceclassic twin: lc-153binary-search
A monitoring agent stores the timestamps of its latest readings in a ring buffer. New readings overwrite the oldest slot. Once the buffer wraps, the timestamps read as an increasing list that starts in the middle, such as 40, 50, 60, 10, 20, 30.
A dashboard asks about ranges of slots. For each range, what is the oldest timestamp, which is the smallest value in those slots?
Write lowest_in_slices(readings, slices).
readings holds different timestamps. It is an increasing list that was rotated by some amount, possibly 0.[l, r] covers the slots l to r, both included.readings[l] to readings[r].Input: readings = [40, 50, 60, 10, 20, 30], slices = [[0, 5], [0, 2], [3, 5], [1, 4], [2, 3], [4, 4]]
Output: [10, 40, 10, 10, 10, 20]Take the slice [1, 4]: the readings 50, 60, 10, 20. The window [lo, hi) starts as [1, 4): slot 4, the last slot of the slice, is a possible answer that is never a middle. Compare the middle with readings[hi].
| Step | lo | hi | mid | readings[mid] | readings[hi] | Decision |
|---|---|---|---|---|---|---|
| 1 | 1 | 4 | 2 | 60 | 20 | 60 > 20, the break is right of mid, so lo = 3 |
| 2 | 3 | 4 | 3 | 10 | 20 | 10 > 20 is false, so hi = 3 |
| end | 3 | 3 | the smallest value is readings[3] = 10 |
The whole buffer, slice [0, 5], also gives 10. The slice [0, 2] holds 40, 50, 60, which is sorted, so its smallest value is the first one, 40. The slice [3, 5] gives 10, the slice [2, 3] gives 10, and the slice [4, 4] gives 20.
Input: readings = [7], slices = [[0, 0]]
Output: [7]With one slot, the only slice is that slot.
Input: readings = [1, 2, 3, 4], slices = [[0, 3], [1, 2], [3, 3]]
Output: [1, 2, 4]A rotation of 0 leaves the list sorted, so the smallest value of a slice is its first slot, readings[l].
1 ≤ readings.length ≤ 100,000, and all readings are differentreadings is a list in increasing order that was rotated: the first part moved to the end. A rotation of 0 is allowed0 ≤ slices.length ≤ 100,000, and each slice is [l, r] with 0 ≤ l ≤ r < readings.length0 ≤ readings[i] ≤ 1,000,000,000 (timestamps in seconds)Looking at every slot of every slice costs up to n × q steps, which is 10^10 when both are 100,000. Inside a slice, the readings are two sorted runs at most, so one comparison with the last slot of the window rules out half of it. That takes about 17 steps per slice.