Binary Search on Arrays

Search sorted and rotated arrays in O(log n), find first and last occurrences, and write a bug-free binary search every time.

Intermediate · about 6 hours · difficulty 3/5

Learn first: Sorting Algorithms and Custom Sorts

Binary search is short to write and easy to get wrong. Learn one template and use it everywhere.

One reliable template

Search for the first index where a condition becomes true (lower bound). Keep lo and hi so the answer is always inside [lo, hi], use mid = lo + (hi - lo) / 2, and shrink until lo == hi. Every variant below is a choice of condition.

Variants

  • First and last position of an element (two lower-bound searches).
  • Search insert position, floor and ceiling.
  • Rotated sorted array: one half is always sorted; decide which half the target is in.
  • Find minimum in a rotated array, peak element (compare mid with mid + 1).
  • 2D matrix: treat a row-major sorted matrix as one array, or walk from the top-right corner for row-and-column sorted matrices.
  • Median of Two Sorted Arrays: binary search on the partition (a hard classic).

Pitfalls

  • (lo + hi) / 2 overflows for large ints; use lo + (hi - lo) / 2.
  • Infinite loops when lo = mid and mid rounds down. Match the rounding to the update.
  • Rotated arrays with duplicates break the O(log n) guarantee.

You are ready to move on when you can solve Search in Rotated Sorted Array and Find First and Last Position without a single off-by-one bug on the first submission.

Key concepts

  • Lower bound and upper bound
  • Loop invariants
  • First and last occurrence
  • Rotated sorted arrays
  • Peak element
  • Search in 2D matrix
  • Median of two sorted arrays

Mini project

Solve these 10 in 7 days, log time and pattern: Binary Search, Search Insert Position, Find First and Last Position, Search in Rotated Sorted Array, Search in Rotated Sorted Array II, Find Minimum in Rotated Sorted Array, Find Peak Element, Single Element in a Sorted Array, Search a 2D Matrix, Median of Two Sorted Arrays.

Check yourself

In a rotated sorted array, how do you decide which half to discard after computing mid?

Free resources