Data Structures & Algorithms · Module 7 · Lesson 21 min read

Binary Search

How it works

On sorted data, look at the middle item:

  • equal → found;
  • target bigger → search the right half;
  • target smaller → search the left half.

Each step halves the search space, so it's O(log n): about 20 steps for a million items, 30 for a billion.

The template

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

Variations interviewers love

  • First or last occurrence of a repeated value: keep searching after a match.
  • Insertion point: Python's bisect.bisect_left(a, x).
  • A rotated sorted array: decide which half is properly sorted.
  • Binary search on the answer: search over possible answers when you can check "is X enough?". Examples: the minimum speed to finish on time, the smallest maximum load, the square root.

Common bugs

  • lo < hi vs lo <= hi, and hi = mid vs mid - 1, which cause off-by-one errors and infinite loops. Pick one template and stick to it.
  • Forgetting that the data must be sorted.

💡 If you can phrase a problem as "find the smallest X such that check(X) is true", and check goes false → true only once, binary search works.

Example

Python
import bisect

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

def first_occurrence(a, target):
    i = bisect.bisect_left(a, target)
    return i if i < len(a) and a[i] == target else -1

def int_sqrt(n):                      # binary search on the answer
    lo, hi = 0, n
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if mid * mid <= n:
            lo = mid
        else:
            hi = mid - 1
    return lo

nums = [2, 5, 5, 5, 8, 12, 16, 23]
print(binary_search(nums, 12))       # 5
print(first_occurrence(nums, 5))     # 1
print(int_sqrt(50))                  # 7
print(bisect.bisect_left(nums, 9))   # 5 → where 9 would be inserted