Module 6 · Lesson 1 · ~25 min
Everyone learns binary search as "find a value in a sorted array." That's the warmup. The real interview skill is recognizing it in disguise — when the answer space itself is searchable, even though no array exists.
"I'm thinking of a number between 1 and 1000. Each guess, I'll tell you higher or lower." You don't guess 1. You guess 500. They say "higher." Now you know it's 501–1000. You guess 750. Half the space falls away every guess. Even at 1000 numbers, you need only 10 guesses. log₂(1000) ≈ 10.
That's binary search. Each step halves the search space. Halving repeatedly is what gives you O(log n).
def bsearch(arr, target):
lo, hi = 0, len(arr) - 1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == target: return mid
if arr[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1
# O(log n) time, O(1) space
function bsearch(arr, target) {
let lo = 0, hi = arr.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (arr[mid] === target) return mid;
if (arr[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
// O(log n) time, O(1) space
function bsearch(arr: number[], target: number): number {
let lo = 0, hi = arr.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (arr[mid] === target) return mid;
if (arr[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
// O(log n) time, O(1) space
Three ways to write the loop: lo <= hi with hi = mid - 1, or lo < hi with hi = mid. They are not interchangeable. Pick one template and use it consistently. Most interviewers accept either as long as you can defend it with the loop invariant.
Many problems aren't sorted arrays at all, but the answer space has a monotonic predicate — a function that's False below some threshold and True above it. Binary search the threshold.
Example: "What's the smallest capacity ship that can deliver all packages within D days?" The answer space is "ship capacity from 1 to sum(weights)." For each candidate capacity, you can check in O(n) whether D days is enough. Capacities below the answer are False, capacities above are True. Binary search the boundary.
def ship_within_days(weights, days):
def can_ship(cap):
d, load = 1, 0
for w in weights:
if load + w > cap: d += 1; load = 0
load += w
return d <= days
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = (lo + hi) // 2
if can_ship(mid): hi = mid
else: lo = mid + 1
return lo
# O(n log W) where W = sum(weights)
function shipWithinDays(weights, days) {
function canShip(cap) {
let d = 1, load = 0;
for (const w of weights) {
if (load + w > cap) { d++; load = 0; }
load += w;
}
return d <= days;
}
let lo = Math.max(...weights);
let hi = weights.reduce((a, b) => a + b, 0);
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (canShip(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
}
// O(n log W) where W = sum(weights)
function shipWithinDays(weights: number[], days: number): number {
function canShip(cap: number): boolean {
let d = 1, load = 0;
for (const w of weights) {
if (load + w > cap) { d++; load = 0; }
load += w;
}
return d <= days;
}
let lo = Math.max(...weights);
let hi = weights.reduce((a, b) => a + b, 0);
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (canShip(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
}
// O(n log W) where W = sum(weights)
"Find the smallest / largest / minimum X such that condition Y holds." Plus: condition Y is monotonic in X (if Y is True at X=k, it's True at X=k+1, or vice versa). That's binary search on the answer space.
| Problem keyword | What you binary-search |
|---|---|
| "Find target in sorted array" | The index |
| "First / last occurrence of target" | The boundary index |
| "Smallest capacity / max weight / minimum days" | The answer value itself |
| "Find peak / find rotation point" | The transition index |
| "Median of two sorted arrays" | The partition point |
| "Square root of n without using sqrt" | The integer answer |