Binary search · Easy
A report displays how many records fall within an inclusive numeric band. Keys are already sorted and may repeat. The service should count the band without scanning or materializing the matching records.
Count all entries between the supplied lower and upper bounds including both endpoints.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], low: integer, high: integer }
Fields
- nums is already sorted in nondecreasing numeric order. Do not sort it again.
- low and high are inclusive integer endpoints with low <= high.
Output
Return value
- Return an integer count of entries, not distinct values. Duplicates at either endpoint count.
- An empty array or a band containing no entries returns 0.
Constraints
- 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000.
- All totals and counts fit exactly in a safe JSON integer.
- -2000000000 <= low <= high <= 2000000000.
Examples
Example 1
{
"high": 4,
"low": 2,
"nums": [
1,
2,
2,
4,
4,
6
]
}Returns
4Example 2
{
"high": 2,
"low": 2,
"nums": [
2,
2,
3
]
}Returns
2Required complexity
O(log(n + 1)) search time and O(1) auxiliary space