Find First and Last Position of Element in Sorted Array⚓︎
Description⚓︎
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 <= 10^5-10^9 <= nums[i] <= 10^9numsis a non-decreasing array.-10^9 <= target <= 10^9
Solution⚓︎
Binary Search Template 1⚓︎
Another way of writing:
Binary Search Template 2⚓︎
Notes⚓︎
1. Index of the first element greater than or equal to x: lower_bound(x)⚓︎
This operation finds the position of the first element in a sorted array that is not less than (i.e., greater than or equal to) a specified value x.
Explanation: The lower_bound function in C++ returns an iterator pointing to the first element in the range [first, last) that is not less than x. If all elements are less than x, it returns an iterator to the end of the range.
C++ Code Example:
2. Index of the first element greater than x: can be treated as the index of the first element greater than or equal to x+1, lower_bound(x+1)⚓︎
Explanation: By searching for x+1, we effectively find the first element that is strictly greater than x.
C++ Code Example:
3. Index of the last element less than x: can be treated as one position to the left of the index of the first element greater than or equal to x, lower_bound(x) - 1⚓︎
Explanation: To find the last element that is less than x, we find the position of the first element that is greater than or equal to x and then subtract one.
C++ Code Example:
4. Index of the last element less than or equal to x: can be treated as one position to the left of the index of the first element greater than or equal to x+1, lower_bound(x+1) - 1⚓︎
Explanation: This is similar to the previous case, but we are interested in the last element that is less than or equal to x. We achieve this by looking for x+1 and then stepping back one position.
C++ Code Example: