Plain binary search stops at any match. When the list contains duplicates you often need the boundaries: where does a run of equal values start and end? The trick is to keep searching even after you hit the target.
A teacher's mark sheet nums is sorted in non-decreasing order, and several students may share a mark. For one mark target, report the stretch of the sheet it fills: return [first, last], the index where target first appears and the index where it last appears. If nobody scored target, return [-1, -1].
Examples
Input: nums = [2, 4, 4, 4, 9, 11], target = 4
Output: [1, 3]
Input: nums = [2, 4, 4, 4, 9, 11], target = 7
Output: [-1, -1]
Constraints
0 <= len(nums) <= 10**4- Aim for O(log n) time. A linear scan is O(n) and misses the technique; do not use the
bisectmodule.
Goals
- Adapt binary search to keep going after finding a match
- Find the leftmost boundary and the rightmost boundary as two separate searches
- Reason about which side mid belongs to when nums[mid] equals the target