Workspace Binary Search
0d
DSA Cheat Sheets

Binary search boundaries

Find the first value at least x. The return value may equal n, indicating the insertion point after the final value.

Candidate range[lo, hi)Index hi is exclusive
a[mid] < xlo = mid + 1Discard the entire left prefix
a[mid] ≥ xhi = midKeep mid as a potential boundary
Terminationlo == hiThe boundary has been located

Python

def lower_bound(a, x):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = lo + (hi-lo)//2
        if a[mid] < x: lo = mid+1
        else: hi = mid
    return lo

C++

int lowerBound(const std::vector<int>& a, int x) {
  int lo = 0, hi = (int)a.size();
  while (lo < hi) {
    int mid = lo + (hi-lo)/2;
    if (a[mid] < x) lo = mid+1; else hi = mid;
  }
  return lo;
}

Java

static int lowerBound(int[] a, int x) {
  int lo = 0, hi = a.length;
  while (lo < hi) {
    int mid = lo + (hi-lo)/2;
    if (a[mid] < x) lo = mid+1; else hi = mid;
  }
  return lo;
}