Lesson 131 of 296
Binary search
What you will learn
- How binary search works and why it is O(log n)
- A correct template and the off-by-one traps
- Finding the first position (lower bound)
- Search in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array
On this page
How it works
On a sorted array, compare the target with the middle item:
- Equal: found.
- Target smaller: it can only be in the left half.
- Target bigger: it can only be in the right half.
Each step halves the search space, so a million items need about 20 steps: O(log n).
Binary Search
Problem (LeetCode 704): return the index of target in a sorted array, or -1.
function binarySearch(nums: number[], target: number): number {
let low = 0;
let high = nums.length - 1;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
const value = nums[mid]!;
if (value === target) return mid;
if (value < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}The off-by-one traps
| Detail | Why |
|---|---|
high = nums.length - 1 | The last valid index |
while (low <= high) | With <, a one-item range would be skipped |
low = mid + 1 and high = mid - 1 | mid has already been checked; without the ±1, the loop can run forever |
low + Math.floor((high - low) / 2) | Avoids overflow in languages with fixed-size integers. In JavaScript Math.floor((low + high) / 2) is fine, but this form shows awareness. |
Always test with: an empty array, one item, the target at the first and last positions, and a missing target smaller or larger than everything.
Lower bound: the first position
Often you need "the first index where nums[i] >= target" (where to insert it, or the first of several equal items). Use a half-open range [low, high):
function lowerBound(nums: number[], target: number): number {
let low = 0;
let high = nums.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (nums[mid]! < target) low = mid + 1;
else high = mid;
}
return low;
}- Returns
nums.lengthif every item is smaller than the target. - To find the first occurrence:
const i = lowerBound(nums, t); return nums[i] === t ? i : -1; - The last occurrence is
lowerBound(nums, t + 1) - 1for integers.
This template (low < high, high = mid) is the one to use for most "find the first position where something becomes true" problems, including Lesson 132.
Search in Rotated Sorted Array
Problem (LeetCode 33): a sorted array of distinct numbers was rotated: [4, 5, 6, 7, 0, 1, 2]. Find the target's index in O(log n).
Key fact: if you split at mid, at least one half is sorted normally. Check whether the target lies inside that sorted half; if so, search there, otherwise search the other half.
function searchRotated(nums: number[], target: number): number {
let low = 0;
let high = nums.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (nums[mid] === target) return mid;
if (nums[low]! <= nums[mid]!) {
if (nums[low]! <= target && target < nums[mid]!) high = mid - 1;
else low = mid + 1;
} else {
if (nums[mid]! < target && target <= nums[high]!) low = mid + 1;
else high = mid - 1;
}
}
return -1;
}nums[low] <= nums[mid] means the left half is sorted (<= handles the case low === mid).
Find Minimum in Rotated Sorted Array
Problem (LeetCode 153): find the smallest item in a rotated sorted array of distinct numbers.
Idea: compare mid with the right end. If nums[mid] > nums[high], the "drop" (and the minimum) is to the right of mid. Otherwise the minimum is at mid or to its left.
function findMinRotated(nums: number[]): number {
let low = 0;
let high = nums.length - 1;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (nums[mid]! > nums[high]!) low = mid + 1;
else high = mid;
}
return nums[low]!;
}O(log n). Note high = mid (not mid - 1): mid itself might be the minimum.
Where binary search hides
- Sorted arrays (obvious).
- Rotated arrays.
- Answer space: "the smallest speed, capacity or size that works" (Lesson 132).
- Any yes/no condition that flips once from false to true across a range.
git bisect(Lesson 97)!
How to say it in an interview
"Binary search halves a sorted search space each step, so it is O(log n). I use low less than or equal to high with mid plus or minus one for exact search, and a half-open lower-bound template with high equals mid to find the first position where a condition becomes true. For a rotated sorted array, one half around mid is always sorted, so I check whether the target lies in that half. For the minimum, I compare mid with the right end to decide which side contains the drop."
Key words
| Word | Meaning |
|---|---|
| Binary search | Halving a sorted search space each step |
| Off-by-one error | A boundary mistake by one position |
| Lower bound | The first index where the value is at least the target |
| Half-open range | [low, high): includes low, excludes high |
| Rotated array | A sorted array shifted so it wraps around |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.