Topics
DSAeasy

Binary Search — the pattern behind O(log n)

When the answer space is sorted, halving it each step beats scanning everything.

Binary search is the first pattern that teaches you to stop linear scanning when the input has order.

When to use it

Template (lower bound)

python
def lower_bound(nums: list[int], target: int) -> int:
    lo, hi = 0, len(nums)
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

Complexity

ApproachTimeSpace
Linear scanO(n)O(1)
Binary searchO(log n)O(1)

Interview tip

Say the invariant out loud: "Everything before lo is too small; everything from hi onward is valid." That one sentence separates a memorized template from someone who understands why it works.

Common mistakes