Recognizing Hidden Binary Search Prompts
When candidates hear "binary search," most look for a sorted array in the input. As highlighted in the Ace Hired roadmap guide, binary search variants remain one of the most frequent failure clusters in technical screens precisely because the input array itself is often unsorted.
The telltale phrasing is optimization under a constraint: "find the minimum speed to finish within hours," "minimize the largest subarray sum across splits," or "maximize the minimum distance between stalls." Whenever checking whether a guessed answer works is much faster than finding directly, you are looking at binary search on the answer space.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
The Loop Invariant That Kills Off-by-One Bugs
1. Monotonicity over the candidate domain
Suppose every candidate answer in yields a boolean verdict feasible(x). If making larger never breaks feasibility, the predicate produces a clean sequence of False values followed by True values.
As CP-Algorithms notes on predicate binary search, once you have a monotonic function, binary search locates the unique transition index in predicate evaluations.
2. Lower-bound vs. upper-bound midpoint rules
I never guess between lo <= hi and lo < hi. Instead, I commit to one exact loop invariant for finding the first `True` value (minimum feasible answer):
- Initialize
loandhiso the true answer is guaranteed to lie inside[lo, hi]. - Loop
while lo < hi:mid = lo + (hi - lo) // 2rounds down, somid < hialways holds. - If
feasible(mid)isTrue,midcould be the answer, so sethi = mid. - Otherwise
midis impossible, so exclude it withlo = mid + 1.
When lo == hi, the loop exits and lo is the minimum valid answer. What if you instead need the last `True` value (maximum valid cap, such as maximizing minimum spacing)? Flip the update to keep mid on lo = mid and set hi = mid - 1 when invalid, but change mid to (lo + hi + 1) // 2 so lo = mid never stalls in an infinite two-element loop.
What about continuous search over real numbers, such as cutting wooden ribbons or finding square roots to tolerance ? Instead of writing while hi - lo > 1e-7, which can spin forever under floating-point precision loss when magnitudes grow large, I run a fixed count of 80 bisection iterations (for _ in range(80):). Since , fixed iterations shrink any interval below IEEE 754 precision cleanly in constant time without infinite-loop risk.
Binary search also adapts cleanly to rotated sorted arrays, where one half around mid is always monotonically sorted (nums[lo] <= nums[mid] tells you the left side is sorted). Once you identify which half is ordered, checking whether target sits inside that ordered range tells you which half to discard in .
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Working Python Code
Below are two complete implementations: minimum ship capacity over sequential days (min_ship_capacity), and maximum minimum spacing across sorted positions (max_min_distance), showing both lower-bound and upper-bound invariants side by side.
from bisect import bisect_left
def min_ship_capacity(weights: list[int], days: int) -> int:
def feasible(cap: int) -> bool:
used_days = 1
current = 0
for w in weights:
if current + w > cap:
used_days += 1
current = 0
current += w
return used_days <= days
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = lo + (hi - lo) // 2
if feasible(mid):
hi = mid
else:
lo = mid + 1
return lo
def max_min_distance(positions: list[int], count: int) -> int:
pts = sorted(positions)
def can_place(gap: int) -> bool:
placed = 1
last = pts[0]
for x in pts[1:]:
if x - last >= gap:
placed += 1
last = x
if placed >= count:
return True
return False
lo, hi = 1, pts[-1] - pts[0]
while lo < hi:
mid = (lo + hi + 1) // 2
if can_place(mid):
lo = mid
else:
hi = mid - 1
return lo
if __name__ == "__main__":
assert min_ship_capacity([1, 2, 3, 4, 5], 3) == 6
assert min_ship_capacity([3, 2, 2, 4, 1, 4], 3) == 6
assert max_min_distance([1, 2, 8, 4, 9], 3) == 3
sorted_vals = [10, 20, 20, 35]
assert bisect_left(sorted_vals, 20) == 1
print("min_ship_capacity:", min_ship_capacity([1, 2, 3, 4, 5], 3))
print("max_min_distance:", max_min_distance([1, 2, 8, 4, 9], 3))Running this script confirms:
min_ship_capacity: 6
max_min_distance: 3For classic array insertion searches, I prefer the standard library instead of hand-rolling loops: Python's `bisect` module provides bisect_left and bisect_right in comparisons (using __lt__ exclusively). Note that bisect does support a key parameter since Python 3.10, though searching a range of integers without allocating a sequence still uses the explicit loop above.
Complexity Analysis
Let be the input length and be the numeric span hi - lo of candidate answers:
- Time complexity: , because each of the bisection steps evaluates a greedy linear checker in . For
max_min_distance, initial sorting adds once before the loop. - Auxiliary space: for
min_ship_capacitysince the greedy scan uses scalar counters; if sorting a copy of input coordinates.
Even when reaches , iterations, so the multiplier stays small enough to pass strict interview constraints effortlessly.
Common Mistakes and When to Skip Binary Search
Four edge bugs show up repeatedly during whiteboard checks:
- Picking invalid initial bounds: Setting
lo = 1instead ofmax(weights)allowsfeasible(mid)to break silently or accept partial items when an item exceedsmid. - Infinite two-element loop on upper bound: Writing
mid = (lo + hi) // 2together withlo = midhangs forever oncehi == lo + 1. - Breaking greedy order: In shipping or painter-partition problems, items cannot be reordered; sorting
weightscorrupts the problem completely. - Assuming `bisect.insort` is $O(\log n)$: As the Python documentation warns, locating the index takes , yet list insertion shifts elements in .
I skip binary search on the answer whenever the decision predicate is non-monotonic (for instance, convex valleys where ternary search or calculus applies, or subarrays with negative elements where feasibility flickers True and False). If checking feasibility requires exponential backtracking, binary search around it rarely helps either.
Practice Problems
Test both invariant directions on these two benchmark problems:
- Koko Eating Bananas: Practice lower-bound answer search with integer ceiling division
((p + speed - 1) // speed). - Capacity To Ship Packages Within D Days: Practice tight initial bounds
[max(weights), sum(weights)]and greedy partition validation.
