sagelearnai

Binary Search

Signal: sorted data, "find the first/last position where…", "minimum value such that…", O(log n) expected, or a search space of possible answers with a monotonic yes/no test.

Core idea: if a predicate is monotonic over the search space (false, false, …, false, true, true, …), you can find the boundary by testing the middle and discarding half each step: O(log n).

One template to rule them all

Find the first index where ok(i) is true in [lo, hi]:

python
def first_true(lo, hi, ok):
    while lo < hi:
        mid = (lo + hi) // 2        # lower middle
        if ok(mid):
            hi = mid                # mid might be the answer; keep it
        else:
            lo = mid + 1            # mid is definitely not the answer
    return lo                       # lo == hi == first true (if any)
  • Searching sorted arrays: ok(i) = a[i] >= target gives the insertion point (bisect_left).
  • Binary search on the answer: ok(x) = "can we finish with capacity/speed/time x?", as in Koko Eating Bananas, shipping capacity, or splitting arrays.
Classic bugs
  • Infinite loop: using lo = mid with a lower middle. Pair hi = mid with lo = mid + 1.
  • Overflow in fixed-width languages: write mid = lo + (hi − lo) / 2.
  • Off-by-one in hi: decide whether hi is inclusive (while lo <= hi) or exclusive (while lo < hi) and stay consistent.

Problems

  1. Binary Search (Easy): Classic lo/hi/mid
  2. Search Insert Position (Easy): First index with nums[i] ≥ target (lower bound)
  3. Search a 2D Matrix (Medium): Treat the matrix as one sorted array of m·n
  4. Find First and Last Position of Element in Sorted Array (Medium): Two binary searches: lower bound and upper bound
  5. Find Peak Element (Medium): Move toward the higher neighbor — a peak must exist there
  6. Koko Eating Bananas (Medium): Binary search on the answer (speed)
  7. Capacity To Ship Packages Within D Days (Medium): Binary search capacity in [max(w), sum(w)]
  8. Single Element in a Sorted Array (Medium): Pairs start at even indices before the single, odd after
  9. Find Minimum in Rotated Sorted Array (Medium): Compare mid with the right end
  10. Search in Rotated Sorted Array (Medium): One half is always sorted; check if target lies in it
  11. Time Based Key-Value Store (Medium): Per key, sorted (timestamp, value) list; binary search floor
  12. Split Array Largest Sum (Hard): Binary search the largest allowed subarray sum
  13. Median of Two Sorted Arrays (Hard): Binary search the partition of the shorter array
  14. First Bad Version (Easy): Lower bound on a monotonic predicate
  15. Sqrt(x) (Easy): Largest m with m·m ≤ x
  16. Valid Perfect Square (Easy): Binary search m with m² == num
  17. Find K Closest Elements (Medium): Binary search the left edge of the size-k window
  18. Search in Rotated Sorted Array II (Medium): Like rotated search, but shrink both ends when lo, mid, hi are equal
  19. Kth Smallest Element in a Sorted Matrix (Medium): Binary search on value; count elements ≤ mid with a staircase walk
  20. Minimum Number of Days to Make m Bouquets (Medium): Binary search the day; count bouquets of k adjacent bloomed flowers
  21. Find in Mountain Array (Hard): Find the peak, then binary search each side (descending on the right)
  22. Search a 2D Matrix II (Medium): Staircase from top-right: eliminate a row or column each step