AlgoViz

Binary search

easy 16 min

Binary search finds a value, a boundary or an insertion point in sorted data by checking the middle and discarding the half that cannot hold the answer.

See it run

Look at the middle, throw away the half that cannot hold the answer, and repeat until one candidate is left.

Operations

Classic search

Find 23, then the missing 6, in [2, 5, 8, 12, 16, 23, 38, 45] with a closed interval. [L] and [R] bound the live range, [MID] is the cell being checked.

Step 1 of 9

Eight sorted values, target 23

  1. 20L
  2. 51
  3. 82
  4. 123
  5. 164
  6. 235
  7. 386
  8. 457R
target = 23comparisons = 0

The array is sorted, which is the whole trick. Start with the full range: L = 0 and R = 7, the last index. Every index from L to R is still a candidate.

Step 1: Eight sorted values, target 23

def binary_search(arr, target):    left, right = 0, len(arr) - 1          # closed interval [left, right]    while left <= right:                    # range is not empty        mid = left + (right - left) // 2    # overflow-safe middle        if arr[mid] == target:            return mid                      # found it        elif arr[mid] < target:            left = mid + 1                  # drop mid and everything left of it        else:            right = mid - 1                 # drop mid and everything right of it    return -1                               # range is empty: not thereprint(binary_search([2, 5, 8, 12, 16, 23, 38, 45], 23))   # 5print(binary_search([2, 5, 8, 12, 16, 23, 38, 45], 6))    # -1
Time
O(log n)
Space
O(1)
find 23
2 comparisons
linear scan
6 comparisons

Each comparison removes half the candidates. Loop while left <= right, move to mid + 1 or mid - 1, and return -1 once the pointers cross.

In the real world

The same binary search doing real jobs. Pick one and step through it.

A friend picks a number from 1 to 100 and answers higher or lower. Always guessing the middle finds it in at most 7 guesses.

Step 1 of 3

Guess the middle: 50

  1. 1L
  2. …
  3. 50MID
  4. …
  5. 100R
guesses = 1

The secret is 37. The range is 1 to 100, so guess 1 + (100 - 1) // 2 = 50. Answer: lower. Half the numbers are gone in one guess.

Step 1: Guess the middle: 50

lo, hi, secret, guesses = 1, 100, 37, 0while lo <= hi:    guess = lo + (hi - lo) // 2    guesses += 1    if guess == secret:        break    if guess < secret:        lo = guess + 1     # "higher"    else:        hi = guess - 1     # "lower"print(guess, guesses)      # 37 3

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Computing mid as (left + right) // 2 in fixed-width languages

    major

    In Java, C, C++ or with NumPy int32 values, left + right can exceed 2³¹ − 1 and wrap to a negative number, so mid becomes a negative index. Python integers never overflow, but the safe form costs nothing and is what interviewers expect.

    Wrong
    mid = (left + right) // 2          # overflows when left + right > 2**31 - 1 in Java/C++
    Right
    mid = left + (right - left) // 2   # right - left always fits
  • Using < with a closed interval

    critical

    With right = len(arr) - 1 the last candidate is checked when left == right. A strict < skips it, so a one-element array, or a target at the final position, is reported missing.

    Wrong
    left, right = 0, len(arr) - 1while left < right:                # misses the case left == right    ...
    Right
    left, right = 0, len(arr) - 1while left <= right:               # closed [left, right]: both ends are candidates    ...
  • Mixing templates: right = len(arr) with <=

    critical

    Half-open initialisation with a closed-interval loop lets mid reach len(arr), which raises IndexError when the target is bigger than every value.

    Wrong
    left, right = 0, len(arr)while left <= right:    mid = left + (right - left) // 2    if arr[mid] == target:         # IndexError when mid == len(arr)        ...
    Right
    left, right = 0, len(arr)while left < right:                # half-open [left, right): stop when empty    mid = left + (right - left) // 2    ...
  • Setting left = mid with a floor midpoint

    critical

    When right = left + 1, the floor midpoint equals left. If that branch sets left = mid, nothing changes and the loop never ends. Either move past mid, or round the midpoint up when the left side keeps mid.

    Wrong
    while left < right:    mid = left + (right - left) // 2    if ok(mid):        left = mid                 # stuck when right == left + 1    else:        right = mid - 1
    Right
    while left < right:    mid = left + (right - left + 1) // 2   # round up    if ok(mid):        left = mid    else:        right = mid - 1
  • Returning on the first match when duplicates matter

    major

    With duplicates, the classic search returns whichever copy mid lands on first. For the first or last occurrence, save the index and keep shrinking toward that side.

    Wrong
    if arr[mid] == target:    return mid                     # any copy, not necessarily the first
    Right
    if arr[mid] == target:    result = mid                   # remember it    right = mid - 1                # and keep looking left
  • Binary searching data that is not sorted

    critical

    Discarding half the range is only safe when order tells you which half cannot hold the answer. On unsorted data the search silently returns wrong answers. Sort once (O(n log n)) if you will search many times; otherwise scan.

    Wrong
    binary_search([9, 2, 7, 4, 5], 4)   # -1, although 4 is there
    Right
    data = sorted([9, 2, 7, 4, 5])        # [2, 4, 5, 7, 9]binary_search(data, 4)                 # 1

Interview tips

  • How to explain it

    • Binary search finds a target in sorted data by repeatedly halving the search space; each comparison discards half the candidates.
    • That gives O(log n) time and O(1) space: about 20 comparisons for a million items.
    • It needs sorted data or, more generally, a monotonic yes or no condition.
    • State your interval first: closed [left, right] or half-open [left, right).
  • Spot it in the wild

    • Sorted array, find a value, a boundary or an insertion point.
    • First or last occurrence, count of a value, first element ≥ or > x.
    • Minimise the maximum or maximise the minimum: binary search the answer.
    • Rotated sorted arrays and peak finding: one half is always safe to drop.
  • Debug checklist

    • Loop condition matches the interval: <= for closed, < for half-open.
    • Pointer updates: mid ± 1 when mid is ruled out, right = mid when it may be the answer.
    • Return value: mid, -1, left or a saved result.
    • Test empty, one element, target below all, above all, and duplicates.
  • Watch out

    • left = mid with a floor midpoint can loop forever.
    • right = len(arr) belongs with while left < right, never with <=.
    • Linked lists have no random access: reaching the middle is O(n).