Leetcode 34. Find First and Last Position of Element in Sorted Array
Given an array of integers nums
sorted in non-decreasing order, find the starting and ending position of a given target
value. If the target is not found in the array, return [-1, -1]
.
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]
[-1, -1]
With these clarifications, we can move to our strategy.
We can use binary search to find the positions efficiently:
Finding the first occurrence: Use binary search to find the leftmost index of the target.
Finding the last occurrence: Use binary search to find the rightmost index of the target.
target
is found.target
is found.Using binary search will help us achieve this in O(log n)
time complexity for both operations.
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result(2, -1);
int left = 0, right = nums.size() - 1;
// Find the first occurrence
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
// Check if the target is found
if (left < nums.size() && nums[left] == target) {
result[0] = left;
}
left = 0, right = nums.size() - 1; // reset for finding last occurrence
// Find the last occurrence
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
// Check if the target is found
if (right >= 0 && nums[right] == target) {
result[1] = right;
}
return result;
}
};
// Example Usage
int main() {
Solution solver;
vector<int> nums = {5,7,7,8,8,10};
int target = 8;
vector<int> result = solver.searchRange(nums, target);
cout << "[" << result[0] << ", " << result[1] << "]" << endl;
return 0;
}
The solution involves performing a binary search twice:
O(log n)
O(log n)
Since each binary search is logarithmic with respect to the size of the array n
, the overall time complexity is O(log n)
. This ensures an efficient search even for the largest possible input sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?