Skip to content
Lesson 6 of 10 · Coding Interview Prep: Data Structures and Algorithms

Binary search

Halve the search space each step on sorted data, and on any yes/no answer that flips once.

24 min

Binary search finds a target in a sorted list in O(log n) by repeatedly checking the middle and throwing away half. For a million items that is about 20 steps instead of a million.

Use it for "the first position where something is true", which also finds exact matches:

python8 lines
lo, hi = 0, len(a)          # search the half-open range [lo, hi)
while lo < hi:
    mid = (lo + hi) // 2
    if a[mid] < x:          # too small: the answer is to the right
        lo = mid + 1
    else:                   # big enough: the answer is mid or to the left
        hi = mid
return lo                   # the first index where a[lo] >= x

lo ends at the first index with a[lo] >= x, or len(a) if there is none. To check for an exact match, test lo < len(a) and a[lo] == x afterwards. Python's bisect.bisect_left(a, x) does exactly this.

When a[mid] < x, mid itself is ruled out, so lo = mid + 1. When a[mid] >= x, mid might still be the first such index, so keep it: hi = mid. Mixing these up is the classic cause of infinite loops and off-by-one bugs. Test with one and two items.

You can also binary search a number when a yes/no check flips exactly once as the number grows. "What is the smallest ship capacity that delivers all packages in d days?" If capacity c works, any larger one works too. So:

  1. 1.Pick the range of possible answers: from the heaviest package up to the total weight.
  2. 2.Write can_ship(c), which simulates the days in O(n).
  3. 3.Binary search for the smallest c where can_ship(c) is true.

Total time: O(n log(range)). This pattern appears in many "minimize the maximum" and "maximize the minimum" problems.

The search range shrinks by half every time round the loop.

Exercise8 checks
python

Write first_at_least(nums, x): nums is sorted ascending. Return the index of the first item that is greater than or equal to x, or len(nums) if every item is smaller. O(log n): do not use bisect or a linear scan.

Your code must satisfy

  • first_at_least([1, 3, 5, 7], 4)→2middle
  • first_at_least([1, 3, 5, 7], 5)→2exact
  • first_at_least([1, 3, 5, 7], 0)→0before all
  • first_at_least([1, 3, 5, 7], 8)→4after all
  • first_at_least([], 3)→0empty
  • first_at_least([2, 2, 2, 5], 2)→0duplicates take first
starter code2 lines
def first_at_least(nums, x):
    pass
Exercise6 checks
python

Packages with the given weights must ship in order (you cannot reorder them) within days days. Each day the ship carries a consecutive group whose total weight is at most its capacity. Write min_capacity(weights, days): the smallest capacity that gets everything delivered in days days or fewer. Use binary search on the capacity.

min_capacity([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5) is 15.

Your code must satisfy

  • min_capacity([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)→15example
  • min_capacity([3, 2, 2, 4, 1, 4], 1)→16one day
  • min_capacity([3, 2, 2], 3)→3a day each
  • min_capacity([3, 2, 2, 4, 1, 4], 3)→6three days
  • min_capacity([7], 2)→7single package
  • min_capacity([1, 2, 3, 1, 1], 4)→3two days
starter code2 lines
def min_capacity(weights, days):
    pass
Common misconception

“Binary search works on any list.”

The idea (guess the middle) feels general.

What is actually true

It needs the list to be sorted, or more generally a yes/no property that flips once. On unsorted data, discarding half can discard the answer.

How to catch yourself

Before using it, write down the condition that is false for the first part and true for the rest.

  • Binary search halves the range each step: O(log n) on sorted data.
  • The reliable template finds the first index where a condition becomes true: lo = mid + 1 or hi = mid.
  • You can binary search a numeric answer when a yes/no check flips once, as in "smallest capacity that works".
  • Test with 0, 1 and 2 items to catch off-by-one and infinite loops.
Check yourself

Search checks.

1Numeric answer

About how many steps does binary search need for 1,000,000 sorted items (to the nearest whole number)?

2Multiple choice

In the template, why is it lo = mid + 1 when a[mid] < x?

  • A`mid` is ruled out
  • BTo save memory
  • CPython requires it
  • DIt avoids sorting
3Multiple choice

Which input can binary search work on?

  • AA random list
  • BA sorted list
  • CA list of dicts, unsorted
  • DA set
4Multiple choice

What does the template return when every item is smaller than x?

  • A-1
  • B0
  • C`len(a)`
  • DNone
5Multiple choice

Binary search on the answer needs which property?

  • AThe answers are prime
  • BA yes/no check that flips once as the answer grows
  • CA sorted input list
  • DNegative numbers

Practise this lesson, not just read it

In BiliMind the questions above are marked when you answer, the flashcards come back on a schedule, and the rest of Coding Interview Prep: Data Structures and Algorithms is planned around your week. Free.