KatInterview

Sorted Sensor Readings: Answer Interval Coverage Queries

Heaps, Sorting & SearchAuto-graded · 20 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searcharraystwo-pointers

Last 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 i is covered by interval [lo, hi] when lo <= readings[i] <= hi.
  • Because readings is 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 lo and hi do not need to be values that appear in readings. 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^5
  • 1 <= len(checks) <= 10^5
  • readings is 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.