Skip to content

Lesson 9 of 40Core patterns

Binary Search

Halve the search space each step to find values, boundaries and even answers in O(log n), without off-by-one bugs.

17 min read0/4 questions

Binary search finds an item among a billion sorted ones in about 30 steps. The idea takes a minute to understand, and the details take practice: it is famous for off-by-one bugs, and interviewers know it. Beyond sorted arrays, the same halving idea answers "what is the smallest speed that works?" questions, which is where it really shines.

The halving idea

Think of guessing a number from 1 to 100 with "higher" or "lower" hints. You guess 50, then 25 or 75, and so on. Each guess throws away half of what is left. That is binary search: compare against the middle of the remaining range and keep only the half that can still contain the answer.

It needs one thing: the data must be sorted (or more generally, ordered so that one comparison tells you which half to keep).

Searching for 23
2
0
↑lo
5
1
8
2
12
3
16
4
↑mid
23
5
38
6
56
7
72
8
91
9
↑hi

The range is all 10 items. mid = (0 + 9) // 2 = 4, value 16. 16 is less than 23, so the answer is to the right.

1/4

Each step halves the range, so n items take about log₂ n steps: O(log n) time and O(1) space.

Quick check
About how many comparisons does binary search need, at most, on a sorted list of 1,000,000 items?
Need a nudge? A hint rules out a wrong answer.

The exact template

Here is the classic version for "find the index of target, or -1". Memorise this shape exactly.

Python
def binary_search(nums, target): lo, hi = 0, len(nums) - 1 # hi is the last valid index while lo <= hi: # range [lo, hi] is not empty mid = (lo + hi) // 2 if nums[mid] == target: return mid if nums[mid] < target: lo = mid + 1 # mid is too small, drop it and the left else: hi = mid - 1 # mid is too big, drop it and the right return -1 nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]print(binary_search(nums, 23), binary_search(nums, 7), binary_search([], 1))
Output
Press Run (⌘ Enter) to see what happens.

The discipline that prevents off-by-one bugs: decide what lo and hi mean, and keep that meaning true. Here, the answer (if it exists) is always inside [lo, hi], both ends included. So:

  • The loop runs while that range is non-empty: lo <= hi.
  • When you rule out mid, exclude it: mid + 1 or mid - 1. Writing lo = mid here can loop forever.
Quick check
Someone writes while lo <= hi: but updates with lo = mid instead of lo = mid + 1. With nums = [1, 3] and target = 3, what happens?
Need a nudge? A hint rules out a wrong answer.
ChallengeEasy

Binary Search

Given a list nums sorted in ascending order with no repeated values, and a number target, return the index of target, or -1 if it is not in the list. Your solution must run in O(log n) time.

nums = [-1, 0, 3, 5, 9, 12], target = 9   →  4
nums = [-1, 0, 3, 5, 9, 12], target = 2   →  -1
nums = [5],                  target = 5   →  0

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i], target <= 10^4
  • All values in nums are unique.
  • nums is sorted in ascending order.
def binary_search(nums: list[int], target: int) -> int: # Look at the middle, then throw away the half that cannot hold target. pass

Searching for a boundary

Many questions are not "is it there?" but "where does it start?". Picture the array as a row of answers to a yes/no question, like nums[i] >= target. On sorted data it looks like F F F T T T. You want the first T.

This is the second template. Now hi starts at len(nums) (meaning "no T found, the answer is past the end") and the range is [lo, hi).

Python
def first_true(nums, target): """First index i with nums[i] >= target (len(nums) if none).""" lo, hi = 0, len(nums) while lo < hi: # stop when lo == hi: that is the answer mid = (lo + hi) // 2 if nums[mid] >= target: hi = mid # mid might be the first T, keep it else: lo = mid + 1 # mid is F, the answer is after it return lo nums = [1, 3, 3, 3, 7, 9]print(first_true(nums, 3), first_true(nums, 4), first_true(nums, 100))
Output
Press Run (⌘ Enter) to see what happens.
TemplateRange meaningLoopOn "too small"On "big enough"Use for
Exact match[lo, hi] inclusivelo <= hilo = mid + 1hi = mid - 1find a value or -1
First true[lo, hi) half-openlo < hilo = mid + 1hi = midboundaries, minimum that works

hi = mid is safe in the second template because mid is always strictly less than hi when lo < hi, so the range still shrinks.

Python ships the boundary search in the standard library: bisect.bisect_left(nums, x) is exactly first_true above, and bisect.bisect_right(nums, x) is the first index with nums[i] > x. JavaScript has no built-in equivalent, so you write the loop.

Predict the outputPython

What does this print?

import bisect
nums = [1, 2, 2, 2, 5]
print(bisect.bisect_left(nums, 2), bisect.bisect_right(nums, 2))
Need a nudge? Hints walk you through it.
ChallengeEasy

Search insert position

nums is sorted ascending with no duplicates. Return the index of target if it is present. If not, return the index where it would be inserted to keep the list sorted. Aim for O(log n).

nums = [1, 3, 5, 6], target = 5  →  2
nums = [1, 3, 5, 6], target = 2  →  1
nums = [1, 3, 5, 6], target = 7  →  4
def search_insert(nums: list[int], target: int) -> int: # Find the first index whose value is >= target. pass

Binary search on the answer

Here is the leap. You do not need an array at all. You need a range of possible answers and a yes/no check that flips once.

Koko eats bananas from piles [3, 6, 7, 11] and has h = 8 hours. At speed k she eats up to k bananas from one pile per hour. What is the slowest speed that finishes in time? Speeds go from 1 to 11 (the biggest pile). A faster speed never makes things worse, so "finishes in time" looks like F F F T T T ... across speeds. Find the first T.

Binary search over speeds 1 to 11
1
0
↑lo
2
1
3
2
4
3
5
4
6
5
↑mid
7
6
8
7
9
8
10
9
11
10
↑hi
speed = 6hours = 1+1+2+2 = 6fits = yes

Try speed 6: 6 hours, which fits in 8. Maybe a slower speed works too, so keep 6 and look left.

1/5

The check costs O(n) (one pass over the piles), and you run it log(max pile) times, so the total is O(n log m) where m is the largest pile. The general recipe:

  1. Find the smallest and largest possible answer.
  2. Write works(x) that returns True when x is good enough, and make sure it flips only once.
  3. Run the first-true template over that range.
Put it in order5 steps

Order the steps of binary search on the answer.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
ChallengeMedium

Koko Eating Bananas

There are piles of bananas, piles[i] in pile i, and h hours until the guards return. Each hour Koko picks one pile and eats up to k bananas from it. If the pile has fewer than k left, she finishes it and waits out the rest of that hour. Return the smallest whole-number speed k that lets her eat every banana within h hours.

piles = [3, 6, 7, 11],       h = 8   →  4
piles = [30, 11, 23, 4, 20], h = 5   →  30
piles = [30, 11, 23, 4, 20], h = 6   →  23

A pile of p bananas takes ceil(p / k) hours.

Constraints

  • 1 <= piles.length <= 10^4
  • piles.length <= h <= 10^9
  • 1 <= piles[i] <= 10^9
def min_eating_speed(piles: list[int], h: int) -> int: # Binary search on the answer: the speed k. pass

Rotated sorted arrays

A sorted array that has been rotated, like [4, 5, 6, 7, 0, 1, 2], is still searchable in O(log n). The key fact: when you split at mid, at least one half is properly sorted. Compare nums[mid] with nums[hi]:

  • If nums[mid] > nums[hi], the drop (the minimum) is somewhere to the right of mid.
  • Otherwise the right half is sorted, and the minimum is at mid or to its left.
def find_min(nums):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] > nums[hi]:
            lo = mid + 1     # the drop is to the right of mid
        else:
            hi = mid         # mid could be the minimum
    return nums[lo]

To search for a target, find which half is sorted, check whether the target lies inside that half's range, and keep that half or the other one. Practice both with the find-min-rotated and search-rotated problems.

Common mistakes

  • Mixing the templates: lo < hi with hi = mid - 1, or lo <= hi with hi = mid. Pick one meaning for the range and follow it.
  • Forgetting the data must be sorted (or that works(x) must flip only once).
  • Overflow in (lo + hi) / 2 in languages with fixed-size integers. Python integers do not overflow, and JS numbers are safe up to 2⁵³, but lo + (hi - lo) // 2 is the habit worth showing.
  • Wrong bounds on the answer range, such as starting Koko at speed 0 (division by zero) or ending below the biggest pile.
Key terms
binary search
Repeatedly compare with the middle and keep the half that can still hold the answer. O(log n).
invariant
What lo and hi mean, kept true every iteration, such as "the answer is in [lo, hi)".
first true
The boundary template: find the first index or value where a monotonic yes/no check becomes true.
binary search on the answer
Search over possible answers (speeds, capacities) using a check function instead of an array.
bisect_left
Python's built-in first-index-at-or-after search on a sorted list.
Interview pattern: Binary Search32 problemsSpot it: Sorted data · "minimum x such that…" · rotated arrays · O(log n) asked