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.
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
Example 3:
Input: nums = [], target = 0 Output: [-1,-1]
Constraints:
0 <= nums.length <= 105-109 <= nums[i] <= 109nums is a non-decreasing array.-109 <= target <= 109When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you are given a long sorted list of items and asked to find where a specific target item first appears and where it last appears. The brute force approach involves looking at every single item in the collection from beginning to end to check for the target.
Here's how the algorithm would work step-by-step:
def search_range(sorted_numbers, target_value):
# We record every index where the target appears so we can easily find the bounds later
matched_indices = []
for current_index in range(len(sorted_numbers)):
if sorted_numbers[current_index] == target_value:
matched_indices.append(current_index)
# If the collection of matches is empty, the target was never present in the input array
if len(matched_indices) == 0:
return [-1, -1]
first_position = matched_indices[0]
last_position = matched_indices[-1]
return [first_position, last_position]Instead of scanning the entire collection sequentially, the optimal strategy takes advantage of the fact that the items are already arranged in order. It uses a clever guessing game to rapidly narrow down the search area from both directions independently.
Here's how the algorithm would work step-by-step:
class Solution:
def searchRange(self, nums: list[int], target: int) -> list[int]:
def find_boundary(is_searching_left: bool) -> int:
low_index = 0
high_index = len(nums) - 1
boundary_index = -1
while low_index <= high_index:
mid_index = (low_index + high_index) // 2
if nums[mid_index] > target:
high_index = mid_index - 1
elif nums[mid_index] < target:
low_index = mid_index + 1
else:
boundary_index = mid_index
# Keep searching left to find the earliest occurrence of the target.
if is_searching_left:
high_index = mid_index - 1
else:
# Keep searching right to find the latest occurrence of the target.
low_index = mid_index + 1
return boundary_index
first_position = find_boundary(True)
# Skip the second search if the target does not exist in the collection.
if first_position == -1:
return [-1, -1]
last_position = find_boundary(False)
return [first_position, last_position]| Case | How to Handle |
|---|---|
| Empty or null input array | Check for null or empty array at the start and return [-1, -1] immediately to prevent null pointer exceptions or out of bounds errors. |
| Array with a single element matching the target | Both the left and right binary search pointers will converge on index 0, correctly returning [0, 0]. |
| Array with a single element not matching the target | The binary search will fail to find the target and return [-1, -1] as required. |
| Target is not present in the array | The modified binary search condition will fail to locate the target boundary and return [-1, -1]. |
| All elements in the array are identical and equal to the target | The left binary search will find index 0 and the right binary search will find the final array index, returning [0, n - 1]. |
| Target is smaller than all elements or larger than all elements | The binary search bounds will naturally exhaust outside the valid array indices and return [-1, -1]. |
| Array contains negative numbers and zeros alongside positives | Standard integer comparison used in binary search correctly handles negative ranges and zero without any special transformations. |
| Maximum possible array size leading to integer overflow during mid calculation | Calculate the midpoint using low + (high - low) / 2 instead of (low + high) / 2 to prevent integer overflow. |