Given an array of integers nums
sorted in non-decreasing order, find the starting and ending position of a given target
value.
If target
is not found in the array, return [-1, -1]
.
You must write an algorithm with O(log n)
runtime complexity.
For example:
nums = [5,7,7,8,8,10], target = 8
should return [3,4]
.nums = [5,7,7,8,8,10], target = 6
should return [-1,-1]
.nums = [], target = 0
should return [-1,-1]
.Explain your approach, including time and space complexity, and provide code.
A brute-force approach to solve this problem would involve iterating through the array nums
and checking each element to see if it matches the target
value. If a match is found, we continue iterating to find the first and last occurrences.
start
and end
to -1.nums
from the beginning.nums[i]
equals target
, then:
start
is -1, set start
to i
.end
to i
.[start, end]
.def search_range_brute_force(nums, target):
start = -1
end = -1
for i in range(len(nums)):
if nums[i] == target:
if start == -1:
start = i
end = i
return [start, end]
Since the array is sorted, we can use binary search to find the target value. To find the starting and ending positions, we can perform two binary searches:
left
to 0 and right
to len(nums) - 1
.left <= right
:
mid = left + (right - left) // 2
.nums[mid] == target
:
end
to mid
right = mid - 1
to find if there is any other occurence on the left sidenums[mid] < target
:
left = mid + 1
.right = mid - 1
.left
to 0 and right
to len(nums) - 1
.left <= right
:
mid = left + (right - left) // 2
.nums[mid] == target
:
start
to mid
left = mid + 1
to find if there is any other occurence on the right sidenums[mid] < target
:
left = mid + 1
.right = mid - 1
.[start, end]
.def search_range(nums, target):
def find_leftmost(nums, target):
left, right = 0, len(nums) - 1
index = -1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
index = mid
right = mid - 1 # Continue searching on the left
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return index
def find_rightmost(nums, target):
left, right = 0, len(nums) - 1
index = -1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
index = mid
left = mid + 1 # Continue searching on the right
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return index
left = find_leftmost(nums, target)
right = find_rightmost(nums, target)
return [left, right]
[-1, -1]
.[-1, -1]
.[0, 0]
; otherwise, return [-1, -1]
.