Sorted Sensor Readings: Answer Interval Coverage Queries
Heaps, Sorting & SearchAuto-graded · 20 test casesLast updated
Tests binary search on sorted arrays with duplicates to answer multiple inclusive range queries in O(log n) per query.
A monitoring system records sensor readings in the order they arrive. Because readings are always non-decreasing, the collected values are stored in a sorted array readings, where readings[i] is the value of the i-th measurement.
You are given a list of coverage checks. Each check specifies a closed interval [lo, hi] and asks: which indices in readings hold values that fall inside this interval?
Write a function that processes all checks and returns, for each one, the index of the first matching reading and the index of the last matching reading.
Rules
- A reading at index
iis covered by interval[lo, hi]whenlo <= readings[i] <= hi. - Because
readingsis sorted, all covered indices form a contiguous block. Return the two endpoints of that block as[first, last]. - If no reading falls inside the interval, return
[-1, -1]for that check. - The interval endpoints
loandhido not need to be values that appear inreadings. Either endpoint may lie below the smallest reading or above the largest. - Return one
[first, last]pair per check, in the same order the checks are given.
Constraints
0 <= len(readings) <= 10^51 <= len(checks) <= 10^5readingsis sorted in non-decreasing order; duplicate values are allowed.0 <= readings[i] <= 10^9- For every check,
0 <= lo <= hi <= 2 * 10^9; all values fit in a 32-bit signed integer. - Each check must be answered in O(log n) time, where n =
len(readings). A linear scan per check is too slow at these limits.
Examples
Example 1
Input: sensor_interval_query([1, 3, 3, 5, 8], [[3, 5], [0, 100], [6, 7]])
Output: [[1, 3], [0, 4], [-1, -1]]
Example 2
Input: sensor_interval_query([2, 2, 2, 4, 4, 9], [[2, 2], [3, 4], [4, 20], [0, 1], [10, 15]])
Output: [[0, 2], [3, 4], [3, 5], [-1, -1], [-1, -1]]
Example 3
Input: sensor_interval_query([], [[0, 10]])
Output: [[-1, -1]]
Hints
Hint 1
Because the readings are sorted, all values inside any closed interval [lo, hi] occupy a contiguous slice of the array. Your task reduces to finding the two boundary indices of that slice.
Hint 2
To find the left boundary, look for the first index whose value is >= lo. To find the right boundary, look for the last index whose value is <= hi. Python's bisect module has exactly the right calls for each — think about when to use bisect_left versus bisect_right.
Hint 3
After computing the two boundary indices, a single comparison tells you whether the interval is empty — no special-casing needed for an empty array, out-of-range intervals, or duplicate values at the edges.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Because readings is sorted in non-decreasing order, every value inside a closed interval [lo, hi] occupies a contiguous block of indices. Finding the block means finding its two endpoints, and both can be found with binary search.
Left boundary — first
The first covered index is the smallest i such that readings[i] >= lo. This is exactly what bisect_left(readings, lo) returns: the leftmost position at which lo could be inserted to keep the array sorted, which equals the first index whose value is not less than lo.
Right boundary — last
The last covered index is the largest i such that readings[i] <= hi. bisect_right(readings, hi) gives the first index with a value strictly greater than hi, so subtracting 1 gives the last index whose value is at most hi.
Emptiness check
If first <= last, the block is non-empty and [first, last] is the answer. Otherwise no reading falls in the interval and the answer is [-1, -1]. This single check handles every edge case uniformly:
- An empty
readingsarray: both bisects return 0, solast = -1 < first = 0. - An interval that falls entirely below all readings:
last = -1. - An interval that falls entirely above all readings:
first = len(readings). - A gap between two consecutive readings:
bisect_rightlands beforebisect_left, makinglast < first.
Why the bisect pairing matters
Using bisect_left for lo ensures every duplicate equal to lo is included on the left. Using bisect_right for hi ensures every duplicate equal to hi is included on the right. Swapping either call would silently drop readings at the window edges.
Complexity
- Time: O(q log n) — each of the
qchecks performs two binary searches overnreadings. - Space: O(1) extra beyond the O(q) output list.
A linear scan per check would cost O(n · q), which reaches 10^10 operations at the given limits and is far too slow.
Reference Solution
from bisect import bisect_left, bisect_right
from typing import List
def sensor_interval_query(readings: List[int], checks: List[List[int]]) -> List[List[int]]:
out = []
for lo, hi in checks:
first = bisect_left(readings, lo) # first index with readings[i] >= lo
last = bisect_right(readings, hi) - 1 # last index with readings[i] <= hi
if first <= last:
out.append([first, last])
else:
out.append([-1, -1])
return out
If you prefer to write the binary search by hand, a single lower-bound helper is enough for both boundaries. On integers, finding the upper bound of hi is the same as finding the lower bound of hi + 1:
def lower_bound(arr: List[int], x: int) -> int:
lo, hi = 0, len(arr) # half-open interval [lo, hi)
while lo < hi:
mid = lo + (hi - lo) // 2
if arr[mid] < x:
lo = mid + 1
else:
hi = mid
return lo # first index with arr[i] >= x, or len(arr)
# first = lower_bound(readings, lo_val)
# last = lower_bound(readings, hi_val + 1) - 1
The half-open invariant keeps the loop correct and always terminates because the interval shrinks on every iteration.