mirror of
https://github.com/prdlk/leetcode.git
synced 2026-09-16 23:16:26 +00:00
1.3 KiB
1.3 KiB
Binary Search
Halve a monotonic search space each step → O(log n).
Recognition
- Sorted input + "find / insert position"
- "Minimize the maximum" / "first value where condition flips"
- Answer itself is numeric and checkable → binary search on the answer
Template
function search(nums, target) {
let lo = 0;
let hi = nums.length - 1;
while (lo <= hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid] === target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1; // lo is the insert position
}
First-true boundary
// smallest index where ok(i) is true; ok is false...false true...true
let lo = 0;
let hi = n; // exclusive; n means "never true"
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (ok(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
Most "hard" binary searches are this shape in disguise.
Pitfalls
- Off-by-one: pick
lo <= hiorlo < hiand stay consistent mid = lo + ((hi - lo) >> 1)avoids overflow and floats- No progress → infinite loop: every branch must shrink the range
Recall
- What property must the search space have? (not "sorted" — monotonic)
- Where does
loland when the target is absent? - When do you search the answer space instead of the array?