Algorithms Playbook
PatternTime O(log n) · Space O(1)9 min read

Binary search: find anything in a sorted array in 30 steps

Halve the search space on every step. The classic version, the off-by-one traps, and the variant interviewers love: binary search on the answer.

In short

If the data is sorted (or the answer is monotonic), look at the middle and throw away the half that can't contain the answer. Each step halves the problem: O(log n).

The idea: open the dictionary in the middle

Looking for a word in a paper dictionary, nobody reads from page 1. You open it around the middle, see you went too far, and keep only the half where the word must be. Then you repeat.

That only works because the dictionary is sorted. With sorted data, one comparison tells you which half to discard, so the number of candidates goes 1,000,000 → 500,000 → 250,000… and reaches one in about 20 steps.

Worst-case steps: linear scan vs binary search
Linear scan · O(n)1,000,000Binary search · O(log n)20log scale
Linear scan · O(n)
1,000,000
Binary search · O(log n)
20
Binary is faster by
50,000×
log₂(n)
19.9
Doubling the data doubles the linear scan, but adds just one step to binary search. That's what O(log n) feels like.
Slide n from 10 to a billion. The linear scan grows with n; binary search barely moves.

Watch it run

Step through it, change the target, or type your own sorted array. Watch the range between lo and hi shrink by half on every comparison. The code panel follows along in Python, TypeScript or Java.

Binary search, step by step
Example
Speed
0215283124165236387568729911099lohitarget = 72
1def binary_search(nums, target):
2 lo, hi = 0, len(nums) - 1
3 while lo <= hi:
4 mid = lo + (hi - lo) // 2
5 if nums[mid] == target:
6 return mid
7 if nums[mid] < target:
8 lo = mid + 1
9 else:
10 hi = mid - 1
11 return -1
Start with the whole array: lo = 0 and hi = 10. The answer, if it exists, is somewhere between them.

Variables

lo0
hi10
mid—
target72
Step 1/9· Comparisons: 0
Every comparison throws away half of what's left. 1,000 sorted items need at most 10 comparisons; 1,000,000 need 20; 1,000,000,000 need 30.

The three classic traps

  • `lo <= hi`, not `lo < hi` (in this version). With <, a one-element range is never checked and you miss the answer when it's the last candidate.
  • `lo = mid + 1` and `hi = mid - 1`. If you write lo = mid, a two-element range can loop forever, because mid keeps landing on lo.
  • `mid = lo + (hi - lo) / 2`. (lo + hi) / 2 overflows a 32-bit integer on huge arrays. This exact bug sat in Java's standard library for about nine years until it was found in 2006.

Variants that show up in interviews

Problem shapeWhat changesExample
First / last occurrenceOn a match, keep searching left (or right) instead of returningFirst and last position of a value in a sorted array
Insert position (lower bound)Find the first index where nums[i] >= targetWhere would this value go to keep the array sorted?
Rotated sorted arrayOne half is always sorted: check which, then whether the target is in itSearch in an array rotated at an unknown pivot
Binary search on the answerSearch over possible answers, with a yes/no check that is monotonicMinimum ship capacity to deliver all packages in D days

The last one is the big unlock. If you can write canDo(x) and it's false, false, false… then true, true, true as x grows, you can binary search for the first true, even though there is no array at all.

How to recognise it

  • The input is sorted, or the problem says "in O(log n)".
  • You're asked for the minimum or maximum value that satisfies a condition.
  • A brute force tries every value from 1 to a huge number one by one.
  • The condition flips only once as the value grows (monotonic).

Key takeaways

  • 01Binary search halves the candidates each step: O(log n) time, O(1) space.
  • 02It needs sorted data or a monotonic yes/no condition.
  • 03Keep the invariant "the answer is in [lo, hi]" and update with mid ± 1.
  • 04Binary search on the answer solves many "minimum value such that…" problems.

Check your understanding

1 of 3

What does binary search need from the data?

Related topics