We do a bisect left and bisect right to find the starting item in a sorted array, and then return both ranges.
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
return [self.binary(nums, target, True), self.binary(nums, target, False)]
def binary(self, nums, target, find_left):
l, r = 0, len(nums) - 1
ans = -1
while l <= r:
mid = (l + r) // 2
if nums[mid] < target:
l = mid + 1
elif nums[mid] > target:
r = mid - 1
else:
ans = mid
if find_left:
r = mid - 1
else:
l = mid + 1
return ans