Lesson 3 of 14 · 18m
Binary Search: The Algorithm That Still Breaks
~90% of professionals ship it buggy per Bentley's courses, and Java's `Arrays.binarySearch` carried an overflow for nine years — the invariant is the whole game.
git bisect exists because finding the commit that broke the build among 1,024 candidates takes about 10 checkouts, not 1,024. Mark one good, one bad, and git walks the middle until only the culprit remains. That's binary search over history — and it's the same algorithm running inside bisect.bisect_left, std::lower_bound, and Go's sort.Search.
It's also the algorithm professionals get wrong. Jon Bentley assigned it in courses at Bell Labs and IBM and reported that roughly 90% of the programmers produced a buggy version. The receipts: java.util.Arrays.binarySearch carried an integer-overflow bug for about nine years — mid = (low + high) / 2 wraps negative when low + high exceeds INT_MAX — until Josh Bloch published "Extra, Extra: Nearly All Binary Searches and Mergesorts are Broken" in June 2006. The fix is mid = low + (high - low) / 2 or Java's unsigned shift (low + high) >>> 1. Python's ints don't overflow, but the habit transfers — and the deeper lesson isn't arithmetic, it's that the boundaries are where binary search lives and dies.
The invariant is the whole game
Binary search bugs are boundary bugs, and they come from an unstated interval. Pick one and write it down:
lo, hi = 0, len(a)searches the half-open range[lo, hi)—while lo < hi, andhi = midon the high side. This is whatbisectuses.lo, hi = 0, len(a) - 1searches the closed range[lo, hi]—while lo <= hi, andhi = mid - 1.
Mix them — lo < hi with hi = mid - 1 — and you either skip an element or loop forever. There is no third option; there are only programmers who didn't decide.
from bisect import bisect_left, bisect_right
i = bisect_left(a, x) # first index where a[i] >= x; == len(a) if absent
j = bisect_right(a, x) # first index where a[i] > x
count_of_x = j - i # works because equal keys are contiguousbisect_left returns the insertion point whether or not x exists — check i < len(a) and a[i] == x before claiming a match. bisect.insort does the O(log n) find then the O(n) insert — maintaining a sorted list is find-cheap, insert-expensive, which is why sortedcontainers.SortedList exists for write-heavy workloads.
Searching the answer, not the array
The productive form binary searches a predicate, not data. "What's the smallest ship capacity that delivers all packages in D days" — check(cap) is monotone (bigger capacity never ships slower), so binary search the capacity space between max(weights) and sum(weights). "First bad version" is bisect_left over is_bad(v). Any monotone yes/no function over an integer range — threshold, cutoff, earliest timestamp — is a search space, and each check call replaces a sorted array's element read.
The same move works on files: a 10GB sorted log on disk can be searched by seeking to byte offsets and scanning to the next newline — bisect logic, just with f.seek instead of a[mid].
What to actually do
State [lo, hi) or [lo, hi] before writing the loop. Use bisect in Python — it's C-accelerated and already correct. Test the degenerate cases: empty range, one element, target below everything, above everything. And when the "array" is really a condition — versions, capacities, thresholds — write check(x), confirm it's monotone, and binary search the answer.
Field notes
bisect_leftvsbisect_rightdiffer only on equal elements — for "first ≥ x" use_left, for "first > x" use_right;j - icounts occurrences for free.- A rotated sorted array still binary-searches — one half is always sorted; check which half contains the target and descend there.
bisectreturnslen(a)when x exceeds everything — index bounds are your check, not the function's error.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Finding a Matrix Inverse Without the Pain
Inverting a matrix feels like magic until you see what it's actually doing: solving n systems of equations at once by row-reducing a doubled matrix. The method is mechanical, and once you see it, you don't forget it. The setup Take your matrix A and write the identity next to it — [A | I]. Now row-reduce until the left side becomes the identity. The right side is A⁻¹. That's the whole method: Gaussian elimination on a wider matrix. [A | I] → row operations → [I | A⁻¹] Every operation that t
STRIPS: The 1971 Paper That's Still the Ancestor of Every Game AI Planner
The 1971 Fikes & Nilsson paper that invented STRIPS planning, read firsthand — and the four changes F.E.A.R.'s GOAP made to run it in real time.
Implementing Your Own Garbage Collector in Java: Memory Allocation, Reference Tracking, and GC Algorithms
This guide walks through designing a fixed-size memory pool, implementing reference counting with cycle detection, coding Mark & Sweep, Mark & Compact, and Copying GC algorithms, and wiring root object identification and sweeping into a working CustomGarbageCollector class.
Solana's Proof of History, Explained
As the blockchain concept expands beyond cryptocurrency into software applications, improving transaction-throughput performance has become a critical area of research and development. One of the more visionary improvements in this area is the Proof of History, introduced by the Solana…