Binary Search — O(log n) on sorted data
Binary Search — O(log n) on sorted data
Precondition: the array is sorted (or you can sort it, which is O(n log n)). Repeatedly halve the range until you converge.
Rules to write it correctly
- Invariant — decide what
loandhimean:- Inclusive both (
lo <= hi,hi = mid - 1) — most common. - Half-open (
lo < hi,hi = mid) — better for "find boundary" problems.
- Inclusive both (
- Termination — pick a loop condition that makes the search shrink each iteration or you have an infinite loop.
- Avoid overflow — in Python you don't have to, but in C/Java use
lo + (hi - lo) // 2not(lo + hi) // 2.
Beyond simple search: binary search on the answer
This is the interview-power-move. When you're asked "find the minimum X such that Y holds" and Y is monotonic in X (once true, stays true), binary search the value of X.
Examples:
- Smallest ship capacity to deliver in D days
- Minimum time for K workers to complete tasks
- Minimum spice level everyone can eat
The predicate is a helper function; the outer loop is a binary search over the answer space.
Off-by-one traps
- Empty array — check upfront or ensure the loop handles
lo > hi. - Duplicates — plain binary search returns some index. If you need the leftmost or rightmost, use the boundary variant.
- The
+1onloand-1onhi— miss it and you loop forever.
Try it
- Write
search_range(nums, target)that returns(leftmost_idx, rightmost_idx)of target, or(-1, -1). - Given a list of ship capacities and
Ddays, use binary-search-on-the-answer to find the min capacity that finishes in D days.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Write
binary_search(nums, target)for a sorted list. Return index or -1. Test with[1, 3, 5, 7, 9, 11, 13]:binary_search(nums, 7)(3) andbinary_search(nums, 4)(-1). - Exercise 2
Boundary variant. Given
[1, 2, 2, 2, 3, 4, 5, 5]andtarget = 2, find the LEFTMOST index. On match, save and push hi = mid - 1. Expected: 1. - Exercise 3
Binary search on the ANSWER. Given
weights = [1..10]anddays = 5, find min ship capacity that ships all in 5 days. Search capacities in[max(weights), sum(weights)]. Expected: 15.