Find First and Last Position of Element in Sorted Array

Return the [first, last] indices of target via two boundary binary searches (lower_bound and upper_bound).

Medium
Time O(log n) Space O(1)
LeetCode
3 min read
binary-search

Problem#

Sorted array. Return [first, last] indices of target, or [-1, -1] if absent.

Examples#

  • nums = [5,7,7,8,8,10], target = 8[3, 4]
  • nums = [5,7,7,8,8,10], target = 6[-1, -1]

Constraints#

  • 0 <= n <= 10^5.

Approach#

Two binary searches: lower_bound(target) and upper_bound(target) - 1. If lo == n or nums[lo] != target, return [-1, -1].

Solution#

Find First and Last Position
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
auto lo = lower_bound(nums.begin(), nums.end(), target);
if (lo == nums.end() || *lo != target) return {-1, -1};
auto hi = upper_bound(nums.begin(), nums.end(), target);
return {(int)(lo - nums.begin()), (int)(hi - nums.begin()) - 1};
}
};

Editorial#

lower_bound finds the first index ≥ target; upper_bound finds the first index > target. Their difference is the count of targets; their endpoints minus 1 give first and last index. Standard library handles both in O(log n).

Complexity#

  • Time: O(log n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.