Find the Start and End Indices of a Target in a Sorted Array
Implement searchRange
Given an array
nums sorted in non-decreasing order and an integer target, return the first and last index of target as a two-element array [start, end]. If target isn't present, return [-1, -1].
Solve it in O(log n) time — one binary search finds the leftmost matching index, another finds the rightmost.
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 = [1], target = 1
Output: [0,0]
+ 4 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ nums.length ≤ 10⁴ - ●
-10⁴ ≤ nums[i], target ≤ 10⁴ - ●
nums is sorted in non-decreasing order (duplicates are allowed)
nums =
[5, 7, 7, 8, 8, 10]
target =
8