Problem 375466 · easy · Phase 03 Linear Management & Searching

Count Values Within a Range

binary search · lower bound · upper bound

Given a sorted list nums (duplicates allowed) and two integers lo <= hi, return how many elements x satisfy lo <= x <= hi.

Examples

Input:  nums = [1, 2, 2, 3, 5, 8], lo = 2, hi = 5
Output: 4
Explanation: 2, 2, 3 and 5 are inside the range.

Input:  nums = [1, 2, 2, 3, 5, 8], lo = 4, hi = 4
Output: 0

Constraints

  • 0 <= len(nums) <= 10**6
  • -10**9 <= nums[i], lo <= hi <= 10**9
  • Required time: O(log n) per call. Counting one by one is too slow.

Goals

  • Distinguish the first index >= x from the first index > x
  • Combine two boundary searches into a count
Starting Python…