Skip to the page

Linear patterns · mid

Binary search in JavaScript

Binary search halves a sorted range (or a range of possible answers) each step, giving O(log n). JavaScript has no built-in binary search (indexOf and includes are linear), so you write it, and most bugs come from the loop condition, how lo and hi move, and a mid that is not a whole number.

The notes

What you must know

  • Use one template and stick to 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) >> 1; if (a[mid] < target) lo = mid + 1; else hi = mid; }.
  • First/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 arrays: one half is always sorted; decide which half the target is in.
  • Patience sorting for LIS: a tails array + lowerBound gives O(n log n).
  • mid must be a whole number: (lo + hi) / 2 can be 2.5, and a[2.5] is undefined. Use (lo + hi) >> 1 for array indices (below 2^31) and lo + Math.floor((hi - lo) / 2) for bigger answer ranges. Above 2^53 - 1 (Number.MAX_SAFE_INTEGER) numbers lose precision: use BigInt.
  • There is no built-in binary search in JavaScript: indexOf, includes and findIndex scan the whole array (O(n)). That is why the interviewer wants your own lowerBound.

The red pen

Common traps: mistake → fix

  • Mistake: lo = mid is fine

    Fix: with lo < hi and floor 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.

  • Mistake: Math.floor is optional for mid

    Fix: without it mid can be a fraction, a[mid] is undefined, and the comparisons go wrong.

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