Binary search halves the search space each iteration — O(log n) on a sorted collection. The half-open invariant [low, high) makes every variant consistent: low is inclusive, high is exclusive. Lower-bound finds the first position ≥ target; upper-bound finds the first position > target. Binary search on the answer solves monotonic problems by searching over a solution space rather than an array.
Same template, different predicates for each binary search variant.
For large indices, low+high overflows int. Always use low + (high-low)/2.
The half-open [low,high) invariant with "if pred: high=mid; else: low=mid+1" works for every binary search variant. Memorise one pattern.
"Find minimum speed to deliver packages in D days" → binary search over speed values with a canDeliver(speed) predicate.
Sign in to share your feedback and join the discussion.