The Runtime Theory
easyleetcode#binary-search

Binary Search

Find a target in a sorted array with binary search, halving the search window on each comparison for O(log n) time and O(1) space.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[-1,0,3,5,9,12], 9

out4

in[-1,0,3,5,9,12], 2

out-1

in[5], 5

out0

The machine must find a target in a sorted array and return its index, or -1. Binary search halves the search window each step by comparing the target with the midpoint; every comparison discards half of the remaining elements. The entire problem is getting the midpoint and the bounds right.

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

Steps: (1) maintain an inclusive window [lo, hi], (2) compare the middle element, (3) move one bound past the midpoint and repeat until the window closes.

Time is O(log n): each step halves the range. Space is O(1) for the iterative version.

Trickiest edge cases: the loop bound — lo <= hi with lo = mid + 1 / hi = mid - 1 guarantees progress; lo < hi with unbounded mids can loop forever when the target is absent. Integer overflow on (lo + hi) is a classic bug in C-like languages; lo + (hi - lo) // 2 avoids it. Targets at either end of the array exercise the exit condition exactly.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.