Binary Search: The Invariant, Not the Index Math
Stop memorizing off-by-one fixes. Watch the one fact that stays true on every step and the code writes itself.
The one-sentence version
Binary search keeps a range [lo, hi] and one promise: if the target exists, it is inside that range. Every step throws away half the range while keeping the promise true.
Interviewers rarely care that you know the algorithm. They care whether you can explain why it is correct and handle the edge cases without trial and error. The invariant is how you do that.
Watch it run
Turn on Predict mode and try to call each step before it is revealed. Then switch the target to a value that is not in the array and watch how the loop ends.
What to say out loud
The code
def binary_search(a: list[int], target: int) -> int:
lo, hi = 0, len(a) - 1
while lo <= hi: # range [lo, hi] is non-empty
mid = lo + (hi - lo) // 2 # avoids overflow in fixed-width languages
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1 # target can only be right of mid
else:
hi = mid - 1 # target can only be left of mid
return -1Edge cases the invariant answers for you
| Question | Answer from the invariant |
|---|---|
Why lo ≤ hi and not lo < hi? | A range with one element (lo == hi) can still hold the target, so it must be probed. |
Why mid + 1 and mid - 1? | mid was already checked. Keeping it would risk an infinite loop on a two-element range. |
| Empty array? | hi = -1, so lo ≤ hi is false immediately and we return -1. |
| Duplicates? | Any match may be returned. For the first or last match, keep searching the correct half after a hit. |
Where it shows up beyond arrays
- Binary search on the answer: "smallest capacity that ships all packages in D days". The sorted thing is the feasibility of each candidate.
- Rotated sorted array: one half is always sorted, so check which half and whether the target belongs in it.
- Systems: finding a log offset by timestamp, or the first commit that broke a build (
git bisect).