def find_bound(nums, target, isFirst):
# Initialize the beginning and end indices
begin, end = 0, len(nums) - 1
# Perform binary search
while begin <= end:
# Calculate the middle index
mid = (begin + end) // 2
# Check if the middle element is the target
if nums[mid] == target:
if isFirst:
# Check if it is the first occurrence
if mid == begin or nums[mid - 1] != target:
return mid
else:
end = mid - 1
else:
# Check if it is the last occurrence
if mid == end or nums[mid + 1] != target:
return mid
else:
begin = mid + 1
elif nums[mid] > target:
# Adjust end index for left subarray
end = mid - 1
else:
# Adjust begin index for right subarray
begin = mid + 1
return -1
def search_range(nums, target):
# Find the first occurrence of target
first = find_bound(nums, target, True)
# If the target is not found, return [-1, -1]
if first == -1:
return [-1, -1]
# Find the last occurrence of target
last = find_bound(nums, target, False)
return [first, last]
# Driver code with examples
examples = [
([5, 7, 7, 8, 8, 10], 8),
([5, 7, 7, 8, 8, 10], 6),
([2, 2, 2, 2, 2], 2),
([1, 3, 5, 7], 7),
([1, 3, 5, 7], 4)
]
for nums, target in examples:
result = search_range(nums, target)
print(f"Array: {nums}, Target: {target}, Result: {result}\n")