Skip to Content

Repeatedly halve the search space on a monotone predicate. O(log N).

Data Flow

target = 10
sorted:  [1, 3, 5, 7, 9, 11, 13]

mid=3 arr[mid]=7   too low  -> lo=4
mid=5 arr[mid]=11  too high -> hi=4
mid=4 arr[mid]=9   too low  -> lo=5
lo > hi -> not found

When to use

Code (last false / first true)

def bsearch(arr, target):
    lo, hi = 0, len(arr)
    while lo < hi:
        mid = (lo + hi) // 2
        if arr[mid] < target:  lo = mid + 1
        else:                  hi = mid
    return lo                          # first idx >= target

Pitfalls

Analogy

Looking up a word in a physical dictionary: open the middle, decide left or right, repeat.

Interview tip: If asked “minimum/maximum of something monotone”, do NOT simulate. Binary-search the answer.

Advertisement