Binary search
easy 16 minBinary 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
- 20L
- 51
- 82
- 123
- 164
- 235
- 386
- 457R
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
- 1L
- …
- 50MID
- …
- 100R
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 3Common mistakes
The bugs interviewers watch for, with the fix beside each.
Computing mid as (left + right) // 2 in fixed-width languages
majorIn 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.
Wrongmid = (left + right) // 2 # overflows when left + right > 2**31 - 1 in Java/C++Rightmid = left + (right - left) // 2 # right - left always fitsUsing < with a closed interval
criticalWith 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.
Wrongleft, right = 0, len(arr) - 1while left < right: # misses the case left == right ...Rightleft, right = 0, len(arr) - 1while left <= right: # closed [left, right]: both ends are candidates ...Mixing templates: right = len(arr) with <=
criticalHalf-open initialisation with a closed-interval loop lets mid reach len(arr), which raises IndexError when the target is bigger than every value.
Wrongleft, right = 0, len(arr)while left <= right: mid = left + (right - left) // 2 if arr[mid] == target: # IndexError when mid == len(arr) ...Rightleft, 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
criticalWhen 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.
Wrongwhile left < right: mid = left + (right - left) // 2 if ok(mid): left = mid # stuck when right == left + 1 else: right = mid - 1Rightwhile left < right: mid = left + (right - left + 1) // 2 # round up if ok(mid): left = mid else: right = mid - 1Returning on the first match when duplicates matter
majorWith 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.
Wrongif arr[mid] == target: return mid # any copy, not necessarily the firstRightif arr[mid] == target: result = mid # remember it right = mid - 1 # and keep looking leftBinary searching data that is not sorted
criticalDiscarding 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.
Wrongbinary_search([9, 2, 7, 4, 5], 4) # -1, although 4 is thereRightdata = 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).