Backend Engineer
Senior
programming
Write a function that finds the first and last position of a target value in a sorted array. If the target is not found, return [-1, -1].
Function Signature
def search_range(nums: List[int], target: int) -> List[int]:
Constraints
0 <= nums.length <= 10^5
-10^9 <= nums[i], target <= 10^9
Examples
1. Input:
search_range([5,7,7,8,8,10], 8) Output:
[3, 4] 2. Input:
search_range([5,7,7,8,8,10], 6) Output:
[-1, -1]
```
def search_range(nums: List[int], target: int) -> List[int]:
def find_left(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
def find_right(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] <= target:
left = mid + 1
else:
right = mid - 1
return right
left_idx = find_left(nums, target)
right_idx = find_right(nums, target)
if left_idx <= right_idx:
return [left_idx, right_idx]
else:
return [-1, -1]
```
Trusted by 100+ professionals preparing for interviews
Trusted by 100+ professionals
50+ Company Question Banks
5+ Supported Languages
Practice More Questions Like This
Generate unlimited interview questions with structured answers, code runner, and AI-powered walkthroughs.
Get Started Free