← Back to Algorithms, page 2

algorithms-0027 · Easy fresher

Implement binary search on a sorted list, iteratively and recursively.

Keep a range [lo, hi] that must contain the target if it exists. Compare the middle element: equal means found, smaller means search the right half, larger means search the left half. Each step halves the range, so it takes O(log n) comparisons. The iterative version uses O(1) space; the recursive version uses O(log n) call stack.

Full answer

Problem

Given a sorted list nums and a target, return its index, or -1 if it is absent.

Example: marks [35, 42, 58, 61, 77, 89, 94], target 61 gives 3; target 60 gives -1.

Constraints: 0 <= len(nums) <= 10^5, values distinct and sorted in increasing order.

Brute force

Linear scan: O(n). With 10^5 values and many queries, too slow.

Optimal approach

  1. lo = 0, hi = len(nums) - 1.
  2. While lo <= hi: mid = lo + (hi - lo) // 2.
    • nums[mid] == target: return mid.
    • nums[mid] < target: lo = mid + 1.
    • Otherwise: hi = mid - 1.
  3. Return -1.

Looking up a word in a printed dictionary works the same way: open near the middle, decide which half, repeat.

Why it works

Invariant: if the target is present, its index is in [lo, hi]. Because the list is sorted, nums[mid] < target means everything at or before mid is too small, so lo = mid + 1 keeps the invariant; the other case is symmetric. The range shrinks every iteration, so the loop ends. When lo > hi the range is empty, so the target is absent.

lo + (hi - lo) // 2 avoids integer overflow in languages with fixed-width integers; in Python (lo + hi) // 2 is equally safe. Use //, not /, which would produce a float.

Complexity

O(log n) time. Iterative O(1) space; recursive O(log n) stack. For n = 10^5, at most 17 iterations.

Code

python
def binary_search(nums, target):
    """Index of target in sorted nums, or -1. O(log n) time, O(1) space."""
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2       # same as (lo + hi) // 2; avoids overflow in other languages
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1


def binary_search_recursive(nums, target, lo=0, hi=None):
    if hi is None:
        hi = len(nums) - 1
    if lo > hi:
        return -1
    mid = (lo + hi) // 2
    if nums[mid] == target:
        return mid
    if nums[mid] < target:
        return binary_search_recursive(nums, target, mid + 1, hi)
    return binary_search_recursive(nums, target, lo, mid - 1)


if __name__ == "__main__":
    marks = [35, 42, 58, 61, 77, 89, 94]
    for f in (binary_search, binary_search_recursive):
        assert f(marks, 61) == 3
        assert f(marks, 35) == 0
        assert f(marks, 94) == 6
        assert f(marks, 60) == -1
        assert f([], 5) == -1
        assert f([5], 5) == 0
    print("all tests passed")

Save as a27_binary_search.py and run python3 a27_binary_search.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty list. One element. Target at either end. Target smaller than all or larger than all values. Duplicates: this version returns any matching index; use lower bound to get the first one. Python's bisect module provides tested lower and upper bound functions.

Pattern

Binary search over a sorted range with a clear invariant. The same reasoning extends to lower and upper bounds, rotated arrays and binary search on the answer.

python
def binary_search(nums, target):
    """Index of target in sorted nums, or -1. O(log n) time, O(1) space."""
    lo, hi = 0, len(nums) - 1
    while lo <= hi:
        mid = lo + (hi - lo) // 2       # same as (lo + hi) // 2; avoids overflow in other languages
        if nums[mid] == target:
            return mid
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1


def binary_search_recursive(nums, target, lo=0, hi=None):
    if hi is None:
        hi = len(nums) - 1
    if lo > hi:
        return -1
    mid = (lo + hi) // 2
    if nums[mid] == target:
        return mid
    if nums[mid] < target:
        return binary_search_recursive(nums, target, mid + 1, hi)
    return binary_search_recursive(nums, target, lo, mid - 1)


if __name__ == "__main__":
    marks = [35, 42, 58, 61, 77, 89, 94]
    for f in (binary_search, binary_search_recursive):
        assert f(marks, 61) == 3
        assert f(marks, 35) == 0
        assert f(marks, 94) == 6
        assert f(marks, 60) == -1
        assert f([], 5) == -1
        assert f([5], 5) == 0
    print("all tests passed")

Iterative and recursive versions tested on the same cases, including empty and single-element lists.

Complexity

Time: O(log n). Space: O(1) iterative; O(log n) recursive. For n = 10^5 at most 17 comparisons are needed.

By level

Fresher: Writes the iterative version with correct bounds and tests found, not found and boundary cases. Should test a target that is missing.

Mid: Explains the invariant, closed versus half-open conventions, and lower bound for duplicates. Uses bisect correctly when asked for library code.

Senior: Discusses overflow in other languages, branch-free and cache-friendly layouts, and generalising the invariant to any monotonic predicate. Explains why binary search can be slower than a scan on very small lists.

Key points

  • Keep [lo, hi] as the only place the target can be
  • Compare with the middle and discard half
  • O(log n) time
  • Use integer division
  • Iterative is O(1) space

Common mistakes

  • Using lo < hi with hi = len - 1 and missing the last element
  • Setting lo = mid instead of mid + 1 and looping forever
  • Using / and getting a float index
  • Running it on unsorted data

Follow-ups

  • How do you find the first occurrence of a duplicated value?
  • How would you search a rotated sorted list?
  • What is binary search on the answer?

Tips

  • State the invariant before code
  • Pick one convention (closed or half-open range) and stick to it
  • Test the ends and a missing value

Evaluation rubric

  • Correct loop bounds and updates
  • Clear invariant
  • Correct complexity
  • Handles edge cases