Binary Search

Halve the search space each step to find elements, boundaries and insertion points in sorted or rotated data, with a bug-free template.

Beginner · about 5 hours · difficulty 3/5

Learn first: Sorting Algorithms

Binary search finds a target in a sorted array in O(log n) by comparing with the middle and discarding half. It is simple in idea and notorious for off-by-one bugs, so pick one template and use it consistently.

Think in terms of a predicate

Most binary search problems become: find the first index where a condition becomes true, given the condition is false...false, true...true. For example "first element >= x" is lower_bound. A reliable template:

lo = 0, hi = n        // answer in [lo, hi]
while lo < hi:
  mid = lo + (hi - lo) / 2
  if condition(mid): hi = mid
  else: lo = mid + 1
return lo

Using lo + (hi - lo) / 2 avoids overflow.

Variations

  • First and last occurrence of a value (two boundary searches).
  • Search insert position.
  • Rotated sorted array: one half is always sorted; decide which half the target lies in.
  • Peak element: compare mid with mid + 1 to move toward a larger neighbour.
  • 2D matrix treated as a flattened sorted array.
  • Binary search on real numbers: loop a fixed number of times (like 100) instead of checking equality.

Pitfalls

Infinite loops when lo = mid is used with a floor midpoint, forgetting the "not found" case, and using binary search on data that is not monotonic.

Key concepts

  • Classic search in sorted array
  • Predicate / first-true template
  • lower_bound and upper_bound
  • First and last occurrence
  • Rotated sorted array
  • Peak finding
  • Binary search on reals

Mini project

Solve 8 problems: Binary Search, Search Insert Position, Find First and Last Position, Search in Rotated Sorted Array, Find Minimum in Rotated Sorted Array, Find Peak Element, Search a 2D Matrix, and Sqrt(x).

Check yourself

In a rotated sorted array, how do you decide which half is sorted, and what breaks when duplicates are allowed?

Free resources