Skip to main content

3.3 Find Range

34. Find First and Last Position of Element in Sorted Array

Problem Description

Given a sorted integer array and a target value, find the first and last positions where the target value appears.

Input and Output Example

The input is an array and a value, and the output is the positions of the first and last appearances of the target value (starting from 0). If the value does not exist in the array, both return values should be -1.

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

The number 8 first appears at position 3 and last appears at position 4.

Solution Explanation

This problem can be seen as implementing C++'s lower_bound and upper_bound functions or Python's bisect_left and bisect_right functions. Here, we use a left-closed, right-open interval approach, but a left-closed, right-closed interval would also work.

int lowerBound(vector<int> &nums, int target) {
int l = 0, r = nums.size(), mid;
while (l < r) {
mid = l + (r - l) / 2;
if (nums[mid] < target) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
}

int upperBound(vector<int> &nums, int target) {
int l = 0, r = nums.size(), mid;
while (l < r) {
mid = l + (r - l) / 2;
if (nums[mid] <= target) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
}

vector<int> searchRange(vector<int> &nums, int target) {
if (nums.empty()) {
return vector<int>{-1, -1};
}
int lower = lowerBound(nums, target);
int upper = upperBound(nums, target) - 1;
if (lower == nums.size() || nums[lower] != target) {
return vector<int>{-1, -1};
}
return vector<int>{lower, upper};
}