Tensorum

Binary Search

Lower/upper bounds, rotated arrays and binary search on the answer space.

DSAIntermediate24 hrs8 patterns · 38 problems
0%
your progress

Core idea

Maintain an invariant on [lo, hi) and halve it. For search-on-answer, write feasible(x), prove it is monotone, then find the first x where it holds.

Reach for it when

  • Sorted or rotated-sorted input
  • 'Minimum capacity / maximum speed such that…' (search on the answer)
  • A predicate flips from false to true exactly once

Template

def first_true(lo, hi, feasible):
    # smallest x in [lo, hi) with feasible(x); hi if none
    while lo < hi:
        mid = (lo + hi) // 2
        if feasible(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

Complexity

O(log n) probes; search-on-answer is O(log range × cost of feasible).

Common pitfalls

  • Infinite loops from lo = mid with floor division
  • Mixing closed and half-open intervals
  • Non-monotone predicates

Recognition cues

Lower/Upper BoundRotated ArraySearch on AnswerMatrix SearchPartition / Split