Easybinary-search
Binary Search
Problem (restated)
Given a sorted array of distinct integers and a target, return the index of target or -1.
Intuition
Classic lower-bound binary search on a sorted array.
Approaches
Lower-bound binary search
VerifiedTime O(log n)Space O(1)
Idea. lo=0, hi=n exclusive; while lo<hi mid=…; if nums[mid]<target lo=mid+1 else hi=mid. Check nums[lo].
Walkthrough. nums=[-1,0,3,5,9,12], target=9 → index 4.
Trade-offs. Iterative form avoids recursion depth concerns.
Solution
export function search(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 < nums.length && nums[lo] === target ? lo : -1;
}
export function search(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 < nums.length && nums[lo] === target ? lo : -1;
}
Template connection
Direct application of the Binary Search template.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?