Skip to the page

Linear patterns · mid

Binary search

Binary search halves a sorted range (or a range of possible answers) each step by testing the middle, giving O(log n), and most bugs come from the loop condition and how lo and hi move.

The notes

What you must know

  • Use one template and stay with it: lower bound = first index with a[i] >= target, on the half-open range [lo, hi) with hi = n; while lo < hi: mid = lo + (hi - lo) / 2; if a[mid] < target: lo = mid + 1 else hi = mid.
  • First and last occurrence: lowerBound(target) and lowerBound(target + 1) - 1 (or upperBound - 1).
  • Search on the answer: when a check(x) is monotonic (false, false, true, true), binary search x: ship capacity, minimum speed, smallest divisor.
  • Rotated sorted arrays: one half is always sorted; decide which half the target is in.
  • Ready-made versions: C++ std::lower_bound and upper_bound (first element not less than the value; the range must be partitioned), Python bisect_left and bisect_right, Java Arrays.binarySearch (returns -(insertion point) - 1 when the key is missing, and with duplicates it may return any matching index).
  • Patience sorting for LIS: a 'tails' array plus lowerBound gives O(n log n).
  • (lo + hi) / 2 can overflow a 32-bit int in Java and C++ when lo and hi are large; use lo + (hi - lo) / 2. Python has no overflow.

The red pen

Common traps: mistake → fix

  • Mistake: lo = mid is fine

    Fix: with lo < hi and a rounded-down mid, lo = mid can loop forever; use lo = mid + 1.

  • Mistake: Binary search needs a sorted array

    Fix: it needs a monotonic condition; the answer range itself can be searched.

  • Mistake: The tails array in LIS is the subsequence

    Fix: only its length is correct.

Easy to hard

Questions interviewers ask, easy to hard

  1. Find the first index of target in a sorted array with duplicates.
  2. Return [first, last] positions of target.
  3. Minimum ship capacity to ship all packages in D days.
  4. Longest increasing subsequence in O(n log n).

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview