Easybinary-search
Search Insert Position
Problem (restated)
Given a sorted distinct array, return the index of target, or where it would be inserted to keep order.
Intuition
Classic lower_bound: first index with nums[i] ≥ target.
Approaches
Lower bound binary search
Tested onlyTime O(log n)Space O(1)
Idea. lo/hi half-open. When mid < target, lo=mid+1 else hi=mid. Answer is lo.
Walkthrough. [1,3,5,6], target=5 → 2; target=2 → 1; target=7 → 4.
Trade-offs. Linear scan is O(n); binary search is required pattern practice.
Solution
export function searchInsert(nums: number[], target: number): number {
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid]! < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
export function searchInsert(nums: number[], target: number): number {
let lo = 0, hi = nums.length;
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid]! < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
Reflection
- Which cue made you pick this pattern in under 90 seconds?
- What input would break a wrong invariant?