Find First and Last Position of Element in Sorted Array
Problem (restated)
Find start and end indices of target in a sorted array, or [-1,-1]. O(log n).
Intuition
Two lower_bound searches for target and target+1.
Approaches
Lower & upper bound
UnverifiedIdea. left = lower_bound(target); right = lower_bound(target+1)-1.
Walkthrough. [5,7,7,8,8,10], 8 → [3,4].
Trade-offs. Linear scan violates the log-time constraint.
export function searchRange(nums: number[], target: number): number[] {
const lower = (t: number) => {
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid]! < t) lo = mid + 1; else hi = mid;
}
return lo;
};
const left = lower(target);
if (left === nums.length || nums[left] !== target) return [-1, -1];
return [left, lower(target + 1) - 1];
}
export function searchRange(nums: number[], target: number): number[] {
const lower = (t: number) => {
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid]! < t) lo = mid + 1; else hi = mid;
}
return lo;
};
const left = lower(target);
if (left === nums.length || nums[left] !== target) return [-1, -1];
return [left, lower(target + 1) - 1];
}
Template connection
Two lower bounds from the same template: the first index of target, and the first index of target + 1. The span between them is the range. If the first bound is not target, the answer is [-1, -1].
Reflection
- The same target needs a lower bound and an upper bound. What changes between
hi = midandlo = mid + 1? - A missing target returns
[-1, -1]. Expanding linearly from the first hit can become O(n). Why is that out? - Target at the far left or the far right: can
midwalk off the array?