Binary Search Lower and upper bounds
229. Find First and Last Position of Element in Sorted Array
You are given an array of integers nums, sorted in non-decreasing order, and an integer target. The same
value can appear many times in a row.
Return [first, last], where first is the smallest index that holds target and last is the largest.
If target does not appear in nums, return [-1,-1]. Indexes start at 0.
Example 1
Input: nums = [-4, 0, 3, 3, 3, 8, 11], target = 3
[2,4]Explanation: 3 appears at indexes 2, 3 and 4. The first of them is 2 and the last is 4.
Example 2
Input: nums = [7, 7, 7, 7], target = 7
[0,3]Explanation: Every element is 7, so the answer runs from the first index, 0, to the last, 3.
Example 3
Input: nums = [-10, -6, -6, 1], target = -5
[-1,-1]Explanation: −5 would sit between −6 and 1, but no element equals it, so both entries are −1.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109nums[i] ≤ nums[i + 1](sorted, repeats allowed)-109 ≤ target ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.