Binary Search
- Write one binary search template that never loops forever and never goes off by one, based on an explicit invariant
- Derive lower bound, upper bound, first/last occurrence and insertion point from that template
- Recognize "search on the answer space" problems (minimize the maximum, smallest feasible capacity) and prove the predicate is monotone
- Use
sort.Search,sort.SearchInts,slices.BinarySearchandslices.BinarySearchFunccorrectly - Connect binary search to real systems: as-of lookups, fee tiers, SSTable indexes, consistent-hashing rings,
git bisect
TL;DR
- Think "first index where a monotone predicate becomes true" (
F F F T T T). Every binary search variant is this with a different predicate. - Half-open template:
lo, hi := 0, n;for lo < hi;mid := lo + (hi-lo)/2; ifpred(mid)thenhi = midelselo = mid + 1; answerlo(which is n if nothing is true). - Lower bound = first
a[i] ≥ x; upper bound = firsta[i] > x; count of x = upper − lower; last occurrence = upper − 1. - Search on the answer: if "can we do it with capacity c?" is monotone in c, binary search c. Cost O(log(range) × cost of the check).
- Go standard library:
sort.Search(n, f)is exactly the template;slices.BinarySearch(s, x)returns(lowerBound, found). - Rotated sorted array: at every step at least one half is sorted; decide which, then whether the target lies inside it.
When to reach for it
- Input is sorted (or sorted after rotation) and the expected complexity is O(log n).
- "Find the first/last position", "insert position", "floor/ceiling", "closest value".
- "Minimize the maximum" or "maximize the minimum" (split array, ship packages, allocate workloads).
- "Smallest k such that …" where checking a given k is easy but computing k directly is not.
- The answer is a number in a known range (speed, capacity, rate, days) and a feasibility check exists.
- "Value as of time t" over versioned data (prices, FX rates, configs, balances).
- Real-valued equation with a monotone function (interest rate given a payment) → bisection.
Core concepts
The invariant-based template
Frame every search as a predicate over indexes that is false up to some point and true afterwards. The answer is the boundary.
Invariant for the half-open template: everything left of lo is false, everything at or right of hi is true. The loop shrinks [lo, hi) until it is empty; then lo == hi is the first true.
// firstTrue returns the smallest x in [lo, hi) for which pred(x) is true,
// or hi if there is none. pred must be monotone: false...false true...true.
func firstTrue(lo, hi int, pred func(int) bool) int {
for lo < hi {
mid := lo + (hi-lo)/2 // no overflow, rounds down, so mid < hi
if pred(mid) {
hi = mid // mid may be the answer: keep it in range
} else {
lo = mid + 1 // mid is false: exclude it
}
}
return lo
}
Why it terminates: mid < hi always, so hi = mid shrinks the range, and lo = mid + 1 shrinks it too. The classic infinite loop comes from writing lo = mid with a mid that rounds down. sort.Search computes the midpoint as int(uint(lo+hi) >> 1), another overflow-safe form.
Bounds and occurrences
// lowerBound: first index with a[i] >= x (len(a) if none).
func lowerBound(a []int, x int) int {
return sort.Search(len(a), func(i int) bool { return a[i] >= x })
}
// upperBound: first index with a[i] > x (len(a) if none).
func upperBound(a []int, x int) int {
return sort.Search(len(a), func(i int) bool { return a[i] > x })
}
- Is x present?
i := lowerBound(a, x); i < len(a) && a[i] == x. - Number of copies of x:
upperBound − lowerBound. - Floor (largest ≤ x):
upperBound(a, x) − 1(none if −1). Ceiling (smallest ≥ x):lowerBound(a, x).
The standard library
| Function | Returns | Notes |
|---|---|---|
sort.Search(n, f) | Smallest i in [0, n) with f(i) true, or n | The general template; f must be monotone |
sort.SearchInts(a, x) | Lower bound of x in sorted []int | Also SearchStrings, SearchFloat64s |
slices.BinarySearch(s, x) | (i, found), i is the lower bound | Generic over cmp.Ordered; first occurrence among duplicates |
slices.BinarySearchFunc(s, target, cmp) | (i, found) using cmp(elem, target) int | Search structs by a field; target may have a different type |
Fee tiers are a typical banking use — a sorted table of thresholds, look up the tier containing an amount:
type tier struct {
minAmount int64 // inclusive lower bound, in cents
feeBps int // basis points
}
// feeFor returns the tier containing amount. tiers are sorted by minAmount,
// tiers[0].minAmount == 0, and amount >= 0.
func feeFor(tiers []tier, amount int64) tier {
i, found := slices.BinarySearchFunc(tiers, amount, func(t tier, a int64) int {
return cmp.Compare(t.minAmount, a)
})
if !found {
i-- // the insertion point is just after the containing tier
}
return tiers[i]
}
Search on the answer space
When the question is "what is the smallest capacity / speed / limit that works?", and feasibility is monotone (if c works, every c' > c works), binary search over c with the feasibility check as the predicate. Three things to get right:
- Bounds: the lowest value that could possibly work (e.g. the heaviest single item) and a value that surely works (e.g. the sum of everything).
- Monotonicity: argue it in one sentence before coding.
- Check cost: usually a greedy O(n) simulation, giving O(n log(range)).
Typical disguises: Koko Eating Bananas (minimum speed), Capacity To Ship Packages (minimum capacity), Split Array Largest Sum (minimize the maximum part), Magnetic Force Between Two Balls (maximize the minimum gap). Operational version: "what is the minimum throughput (TPS) that clears tonight's payment backlog before the settlement cut-off?" — simulate the queue for a candidate TPS, binary search the TPS.
Bisection on real numbers
For continuous monotone functions, halve an interval a fixed number of times instead of comparing floats for equality. Solving for an interest rate is the banking example: the payment on an annuity loan increases with the rate, so bisection finds the rate that produces a given payment.
// monthlyRate finds the monthly rate r at which principal is repaid by n
// equal payments of pmt. Assumes principal/n <= pmt < payment at 100%/month.
func monthlyRate(principal, pmt float64, n int) float64 {
payment := func(r float64) float64 {
if r == 0 {
return principal / float64(n)
}
return principal * r / (1 - math.Pow(1+r, -float64(n)))
}
lo, hi := 0.0, 1.0
for range 100 { // fixed iterations: no fragile epsilon checks
mid := (lo + hi) / 2
if payment(mid) < pmt {
lo = mid
} else {
hi = mid
}
}
return (lo + hi) / 2
}
A loan of 10,000 repaid in 12 payments of 888.49 yields ≈1% per month. Production APR calculations follow regulator-defined formulas and decimal arithmetic, but the root-finding underneath is bisection or Newton's method.
Binary search inside real systems
- Versioned data "as of t": FX rate or price at the time of a transaction, configuration in effect at a timestamp, account balance at month-end (prefix sums + binary search, see Arrays & Hashing).
- Storage engines: keys inside a B-tree page and SSTable sparse indexes are binary-searched (Storage Engines: B-Tree vs LSM); Kafka locates a message by binary-searching its offset and time indexes.
- Consistent hashing: find the first virtual node clockwise from a key's hash with
sort.Searchon the sorted ring (Consistent Hashing). - Debugging:
git bisectbinary-searches commit history for the first bad commit — the predicate is "is this commit broken?".
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Binary search on a sorted slice | O(log n), no extra memory, cache-friendly | Requires sorting; O(n) inserts | Static or rarely changing ordered data |
| Hash map | O(1) exact lookups | No floor/ceiling/range queries | Exact-key access only |
| Balanced tree / B-tree | O(log n) lookups and updates, ordered | More memory and code | Ordered data with frequent writes |
| Search on answer | Turns optimization into decision problems | Needs a monotone, cheap check | "Minimum capacity / maximum minimum" problems |
| Bisection | Robust, simple, guaranteed convergence | Linear convergence (one bit per step) | Monotone real functions; Newton's method if the derivative is known and well-behaved |
| Linear scan | Simple, fastest for tiny n | O(n) | n under a few dozen, unsorted data |
In practice
Problem 1 — Find First and Last Position of Element (LeetCode 34)
Problem. In a sorted slice with duplicates, return the first and last index of target, or (−1, −1).
Approach. Lower bound for the first position, upper bound minus one for the last — two sort.Search calls.
func searchRange(nums []int, target int) (first, last int) {
lo := sort.SearchInts(nums, target) // first index with nums[i] >= target
if lo == len(nums) || nums[lo] != target {
return -1, -1
}
hi := sort.Search(len(nums), func(i int) bool { return nums[i] > target })
return lo, hi - 1
}
Complexity. O(log n) time, O(1) space.
Problem 2 — Search in Rotated Sorted Array (LeetCode 33)
Problem. A sorted slice of distinct values was rotated at an unknown pivot ([4,5,6,7,0,1,2]). Find the target's index in O(log n).
Approach. At each step, one of the halves [lo, mid] or [mid, hi] is sorted — compare nums[lo] with nums[mid] to know which. If the target lies inside the sorted half's range, search there; otherwise search the other half. This uses a closed interval [lo, hi] because it returns on an exact match.
func searchRotated(nums []int, target int) int {
lo, hi := 0, len(nums)-1
for lo <= hi {
mid := lo + (hi-lo)/2
if nums[mid] == target {
return mid
}
if nums[lo] <= nums[mid] { // left half is sorted
if nums[lo] <= target && target < nums[mid] {
hi = mid - 1
} else {
lo = mid + 1
}
} else { // right half is sorted
if nums[mid] < target && target <= nums[hi] {
lo = mid + 1
} else {
hi = mid - 1
}
}
}
return -1
}
Complexity. O(log n). With duplicates (LeetCode 81), nums[lo] == nums[mid] gives no information and the worst case degrades to O(n).
Problem 3 — Capacity To Ship Packages Within D Days (LeetCode 1011)
Problem. Packages with given weights must ship in order; each day the ship carries a contiguous run whose total weight is at most its capacity. Find the minimum capacity that ships everything within days.
Approach. Search on the answer. Capacity below the heaviest package is impossible; capacity equal to the total ships in one day. Feasibility is monotone (more capacity never needs more days) and checked greedily in O(n): fill each day until the next package would overflow.
func shipWithinDays(weights []int, days int) int {
lo, hi := 0, 0
for _, w := range weights {
lo = max(lo, w) // must fit the heaviest package
hi += w // one day ships everything
}
canShip := func(capacity int) bool {
needed, load := 1, 0
for _, w := range weights {
if load+w > capacity {
needed++
load = 0
}
load += w
}
return needed <= days
}
return firstTrue(lo, hi+1, canShip)
}
Complexity. O(n · log(sum − max)) time, O(1) space. Same structure: "minimum batch size so nightly settlement files finish in N runs", "minimum workers so the queue drains before cut-off".
Problem 4 — Time Based Key-Value Store (LeetCode 981)
Problem. Set(key, value, timestamp) with increasing timestamps per key, and Get(key, timestamp) returning the value with the largest timestamp ≤ the given one. Read it as "FX rate for EUR/VND as of the transaction time".
Approach. Append versions per key (already sorted by time); answer Get with an upper-bound search and step back one.
type versioned struct {
ts int64
value string
}
// TimeMap answers "value as of ts". Set must be called with increasing ts per key.
type TimeMap struct {
data map[string][]versioned
}
func NewTimeMap() *TimeMap { return &TimeMap{data: make(map[string][]versioned)} }
func (m *TimeMap) Set(key, value string, ts int64) {
m.data[key] = append(m.data[key], versioned{ts: ts, value: value})
}
// Get returns the value with the largest timestamp <= ts.
func (m *TimeMap) Get(key string, ts int64) (string, bool) {
vs := m.data[key]
i := sort.Search(len(vs), func(i int) bool { return vs[i].ts > ts }) // upper bound
if i == 0 {
return "", false // no version at or before ts
}
return vs[i-1].value, true
}
Complexity. Set amortized O(1), Get O(log v) for v versions of the key. In a database the same query is WHERE pair = $1 AND valid_from <= $2 ORDER BY valid_from DESC LIMIT 1 — a B-tree index on (pair, valid_from) makes it a single descent (Indexing).
Practice list
- Easy: Binary Search (704), Search Insert Position (35), First Bad Version (278), Sqrt(x) (69)
- Medium: Find First and Last Position of Element in Sorted Array (34), Search a 2D Matrix (74), Koko Eating Bananas (875), Find Minimum in Rotated Sorted Array (153), Search in Rotated Sorted Array (33), Find Peak Element (162), Time Based Key-Value Store (981), Capacity To Ship Packages Within D Days (1011)
- Hard: Median of Two Sorted Arrays (4), Split Array Largest Sum (410), Find K-th Smallest Pair Distance (719)
Common pitfalls
- Infinite loops from
lo = midwhen mid rounds down. With the half-open template, the false branch is alwayslo = mid + 1. - Mixing templates — a closed
[lo, hi]loop condition with half-open updates, or vice versa. Pick one per problem and state the invariant. - Non-monotone predicates. Binary search silently returns garbage. Symptom: wrong answers on some inputs only.
- Searching data sorted by a different key or order than the comparison you pass (sorted by name, searched by amount).
- Overflow in
(lo + hi) / 2with large index or value ranges; uselo + (hi−lo)/2. - Wrong answer-space bounds: starting
loat 1 instead of the maximum single item, orhitoo small so the true answer is outside the range. - Comparing floats for equality in bisection; iterate a fixed number of times or until the interval is narrower than the required precision.
- Forgetting the "not found" case:
sort.Searchreturns n, andslices.BinarySearchreturns an insertion point — both must be checked before indexing.
Interview angle
- State the invariant out loud ("everything left of lo is false, everything from hi on is true"); interviewers see far fewer off-by-one bugs from candidates who do.
- When a problem says "minimum X such that…", ask yourself whether checking a given X is easy — that is the cue for search on the answer, and saying so early scores points.
- Mention the standard library: "In Go I'd use
sort.Searchhere" shows production fluency; then write the loop anyway if asked. - Follow-ups: duplicates, rotated arrays with duplicates, 2D matrices (treat as a flattened sorted array or start from a corner), unknown size (exponential search: double hi until the predicate is true), and "what if the data does not fit in memory?" (B-tree / sparse index per block).
- Red flags: a linear scan "to be safe", fuzzy loop bounds patched by trial and error, or not knowing why
lo + (hi−lo)/2is used.
Self-check
1. State the invariant of the half-open template and why it terminates.
Every index below lo has a false predicate and every index at or above hi has a true predicate. Each iteration either sets hi = mid (with mid < hi because mid rounds down) or lo = mid + 1 (with mid ≥ lo), so the range [lo, hi) strictly shrinks; when it is empty, lo is the first true index.
2. How do you count occurrences of x in a sorted slice in O(log n)?
upperBound(a, x) − lowerBound(a, x): the first index with a value greater than x minus the first index with a value at least x. In Go: sort.Search(n, func(i int) bool { return a[i] > x }) − sort.SearchInts(a, x).
3. What does slices.BinarySearch return when the value is absent, and how do you use it?
It returns (i, false) where i is the insertion point — the index at which x would be inserted to keep the slice sorted (the lower bound). You can insert with slices.Insert(s, i, x), or use i − 1 as the floor element when i > 0.
4. Why can Capacity To Ship Packages be solved by binary search on the capacity?
Feasibility is monotone: if a capacity c ships everything within D days, any larger capacity does too (the same daily split still fits). So the predicate "c is feasible" is false up to some threshold and true afterwards, and the minimum feasible capacity is the first true value in [max(weights), sum(weights)]. Each check is an O(n) greedy simulation.
5. In a rotated sorted array, how do you know which half is sorted?
Compare the endpoints: if nums[lo] ≤ nums[mid], the rotation point is not inside [lo, mid], so that half is sorted; otherwise [mid, hi] is sorted. Then check whether the target lies within the sorted half's value range to decide where to continue.
6. Scenario: settlement must compute every card transaction's amount in the merchant's currency using the FX rate valid at the transaction time. Rates change every few seconds. How do you design the lookup?
Store rates per currency pair as versions sorted by valid_from (append-only, like the TimeMap), and for each transaction binary-search the latest version at or before its timestamp — O(log v) in memory, or a B-tree index on (pair, valid_from) in the database. For a batch, sort transactions by time and walk rates with two pointers instead (O(n + v)). Store the rate ID used on each transaction for auditability.
Exercise
Implement a ledger helper:
BalanceAt(postings []Posting, t time.Time) int64— postings are sorted by time; precompute prefix sums once and answer each query withsort.Search.MinTPS(arrivals []int, cutoffMinute int) int—arrivals[m]is the number of payments arriving in minute m; find the minimum constant processing rate (payments per minute) that leaves no backlog at the cut-off, usingfirstTruewith a queue simulation as the predicate.- Property test: compare both against brute-force implementations on random inputs with
testing/quickor a seeded random generator.
Done when the property tests pass for 10,000 random cases and you can state the time complexity of each function in terms of postings, queries and the TPS range.
Further reading
- Jon Bentley, Programming Pearls — the column on writing a correct binary search
- Joshua Bloch, "Extra, Extra – Read All About It: Nearly All Binary Searches and Mergesorts are Broken" (Google Research Blog, 2006) — the midpoint overflow bug
- Go documentation:
sort.Searchandslices.BinarySearchFunc - Donald Knuth, The Art of Computer Programming, Vol. 3 — searching ordered tables
Related
- Arrays & Hashing — prefix sums that binary search queries.
- Trees & BSTs — binary search as a dynamic data structure.
- Dynamic Programming — LIS in O(n log n) uses lower bound.
- Consistent Hashing — ring lookup with
sort.Search. - Storage Engines: B-Tree vs LSM — binary search inside pages and indexes.
- Double-Entry Ledger Design — balances as of a point in time.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).