Find First and Last Position of Element in Sorted Array
Medium
Topics
Given a sorted array nums and a target, return [first, last] — the first and last index of target. Return [-1, -1] if it is not found. Must run in O(log n).
Example 1
[3, 4].Input: nums = [5,7,7,8,8,10], target = 8 Output: [3,4]
Example 2
[-1, -1].Input: nums = [5,7,7,8,8,10], target = 6 Output: [-1,-1]
Constraints
- 0 <= nums.length <= 10^5
- nums is sorted in non-decreasing order.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A linear scan finds both ends in O(n), which the sortedness makes unnecessary. The problem explicitly asks for O(log n), so binary search it is — but a single binary search finds some occurrence, not the first or last one, because it stops as soon as it hits the target.
The fix is to keep going. On a match, record the index and then continue searching the side you care about: for the first occurrence, keep moving the upper bound left; for the last, keep moving the lower bound right. Each search still halves the range every step, so each is O(log n) and the pair costs two of them.
That is what the low flag selects: the same routine, with the post-match direction flipped.
Approach
- Binary search recording the last index where the target was seen.
- On a match, narrow toward the left for the first position, toward the right for the last.
- Run it twice and return both;
[-1, -1]if never found.
Dry Run
nums = [5,7,7,8,8,10], target = 8
first occurrence (narrow left on a match):
lo=0 hi=5 mid=2 nums[2]=7 < 8 -> lo=3
lo=3 hi=5 mid=4 nums[4]=8 match, record 4, hi=3
lo=3 hi=3 mid=3 nums[3]=8 match, record 3, hi=2
lo > hi -> first = 3
last occurrence (narrow right on a match):
lo=0 hi=5 mid=2 7 < 8 -> lo=3
lo=3 hi=5 mid=4 match, record 4, lo=5
lo=5 hi=5 mid=5 nums[5]=10 > 8 -> hi=4
lo > hi -> last = 4
answer [3,4]Notice the first search records 4 before finding 3 — the recorded value is overwritten as the search pushes further left, which is why recording rather than returning is the key move.
Complexity
- Time — O(log n): two binary searches, each halving the range.
- Space — O(1): indices only.
Common Pitfalls
- Returning on the first match. That gives an arbitrary occurrence, which is neither bound.
- Finding one end and then scanning linearly for the other. It passes the tests and is O(n) on a run of equal values, which defeats the point.
- Flipping the narrowing direction, so the "first" search drifts right.
- Forgetting the not-found case. The recorded value stays at its initial -1, which is exactly the required answer.
- Using
(lo + hi) / 2in a language wherelo + hican overflow. Safe at these sizes, butlo + (hi - lo) / 2is the habit.
Full Solution — all languages
class Solution:
def searchRange(self, nums, target):
def bound(low):
lo, hi, res = 0, len(nums) - 1, -1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
res = mid
if low:
hi = mid - 1
else:
lo = mid + 1
elif nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return res
return [bound(True), bound(False)]import java.util.*;
class Solution {
public int[] searchRange(int[] nums, int target) {
return new int[]{bound(nums, target, true), bound(nums, target, false)};
}
int bound(int[] nums, int target, boolean low) {
int lo = 0, hi = nums.length - 1, res = -1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (nums[mid] == target) {
res = mid;
if (low) hi = mid - 1;
else lo = mid + 1;
} else if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return res;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> searchRange(vector<int>& nums, int target) {
auto bound = [&](bool low) {
int lo = 0, hi = (int)nums.size() - 1, res = -1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (nums[mid] == target) {
res = mid;
if (low) hi = mid - 1;
else lo = mid + 1;
} else if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return res;
};
return {
bound(true), bound(false)
};
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/ var searchRange = function(nums, target) {
const bound = (low) => {
let lo = 0, hi = nums.length - 1, res = -1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (nums[mid] === target) {
res = mid;
if (low) hi = mid - 1;
else lo = mid + 1;
} else if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return res;
};
return [bound(true), bound(false)];
};