Problem. Given a sorted array nums and a target, return its index, or -1 if absent. O(log n) required.
Brute force — O(n)
A linear scan ignores the sortedness — correct but defeats the point. The whole reason the array is sorted is to permit O(log n).
Optimal — binary search, O(log n)
Maintain an inclusive window [lo, hi]. Each step compares the midpoint to the target and discards half the window.
int search(int[] nums, int target) {
int lo = 0, hi = nums.length - 1; // inclusive bounds
while (lo <= hi) { // <= : lo == hi is still a candidate
int mid = lo + (hi - lo) / 2; // overflow-safe
if (nums[mid] == target) return mid;
else if (nums[mid] < target) lo = mid + 1; // discard left half + mid
else hi = mid - 1; // discard right half + mid
}
return -1;
}
O(log n) time — the window halves every iteration — and O(1) space.
The three details that make it correct
lo <= himatches the inclusivehi = length - 1. Withlo < hiyou'd skip the final single-element window.lo + (hi - lo) / 2avoids theintoverflow that(lo + hi) / 2suffers on huge arrays.mid + 1/mid - 1move strictly pastmid, guaranteeing the window shrinks every iteration so the loop always terminates.