Binary Search

A fast way to find a value in a sorted list by repeatedly cutting the search area in half.

What is it?

Checking items one at a time could take a million checks in a million-item list. If the list is sorted, there's a faster way.

Check the middle item. If it's too big, the answer is in the left half; if too small, the right half. Repeat on whatever is left. This is binary search, and it finds a value among a million items in about 20 checks.

Explain like I'm 10

It's how you find a word in a paper dictionary. You don't start at page 1. You open to the middle, see whether you've gone too far, and jump to the middle of the correct half, repeating until you find the word.

Examples

Binary search implementation

function binarySearch(sortedArray, target) {
  let low = 0;
  let high = sortedArray.length - 1;

  while (low <= high) {
    const mid = Math.floor((low + high) / 2);

    if (sortedArray[mid] === target) return mid;
    if (sortedArray[mid] < target) {
      low = mid + 1; // search the right half
    } else {
      high = mid - 1; // search the left half
    }
  }

  return -1; // not found
}

How it works

Each check rules out half of what's left. From n items you go to n/2, then n/4, then n/8. That halving means only about log2(n) steps, far fewer than checking every item.

[1,3,5,7,9,11,13] — looking for 11
        ↓ check middle (7) → too small → search right half
   [9,11,13]
        ↓ check middle (11) → found!

Why does it exist?

Binary search clearly shows why algorithm choice matters. On sorted data, the same problem goes from O(n) to O(log n), a gap that becomes enormous as data grows.

When to use it

Use binary search when you repeatedly search a large, sorted collection. It turns an O(n) scan into an O(log n) lookup.

When not to use it

If the data isn't sorted and can't easily stay sorted, sorting first costs more than one linear search. For a very small list, just check each item.

Common mistakes

  • Using binary search on unsorted data. It silently gives wrong answers instead of failing.

  • Getting the low/high update backwards, causing an infinite loop or skipped elements.

  • Off-by-one errors in the midpoint or the boundary updates.

Practice exercises

  1. Easy:

    Implement binary search on a sorted array of numbers, returning the target's index.

  2. Medium:

    Change binary search to return the index where a value should be inserted to keep the array sorted, even if it isn't found.

  3. Hard:

    Use binary search to find the smallest number in a sorted array that has been rotated (e.g. [4,5,6,1,2,3]).

Interview questions

What is required for binary search to work?

The data must be sorted. Binary search relies on ruling out half the remaining data with one comparison.

What is the time complexity of binary search?

O(log n), since each step halves the remaining search space.

Why is O(log n) so much better than O(n) for large inputs?

Logarithmic growth is very slow: doubling the input adds just one step, while linear growth doubles the work.

Walk through why binary search takes O(log n) steps: starting with n items, how many remain after each comparison?

Each comparison removes half the range: about n/2 left after 1 step, n/4 after 2, n/2^k after k. The search ends near 1 item, when n/2^k ≈ 1, so k ≈ log₂(n). Steps grow logarithmically, not linearly.

What precondition does binary search require that makes it inapplicable to a linked list, even though a linked list can be sorted?

O(1) random access, to jump straight to the middle of the range. A linked list must walk from the head to reach the middle, O(n), so 'jumping to the middle' costs as much as a full scan and the benefit disappears.

In `const mid = Math.floor((low + high) / 2)`, why does this implementation need `while (low <= high)` rather than `while (low < high)`?

low <= high still checks the case low === high, the last remaining candidate. With low < high, that element is skipped and a target sitting there is wrongly reported 'not found'.

What's the classic overflow bug with `mid = Math.floor((low + high) / 2)` in languages with fixed-width integers, and how do implementations avoid it?

If low + high exceeds the maximum integer (32-bit signed overflow in Java/C++), it wraps to a negative or garbage value and mid is nonsense. The fix is mid = low + Math.floor((high - low) / 2), which never adds the two. It's not a practical concern for array indices in JavaScript, whose numbers are IEEE-754 doubles that represent integers exactly up to 2^53, but it's a real trap in fixed-width-integer languages.

How would you modify binary search to find the leftmost (first) occurrence of a target value that appears multiple times in a sorted array?

On arr[mid] === target, don't return. Record mid as a candidate and keep searching the left half (high = mid - 1) until low > high. The last candidate recorded is the leftmost occurrence. Still O(log n).

Symmetrically, how would you find the rightmost (last) occurrence of a duplicated target?

On arr[mid] === target, record mid and keep searching the right half (low = mid + 1). The last candidate recorded when low > high is the rightmost occurrence.

How would you find the index where a value should be inserted into a sorted array to keep it sorted, even if that exact value isn't present?

Run a normal binary search, but return low instead of -1 when the loop ends. By then low is the first index whose value is >= the target, which is the correct insertion point.

How would you search for a target in a sorted array that's been rotated at an unknown pivot (e.g. `[4,5,6,7,0,1,2]`), while keeping O(log n) time?

Each step, compare arr[low] with arr[mid] to find the normally sorted half. If arr[low] <= arr[mid], the left half is sorted: search it if the target falls in its range, otherwise search the right half. If the right half is the sorted one, do the mirror image. One half is still discarded per step, so it stays O(log n).

In the rotated-array search, why does at least one half always have to be properly sorted, no matter where the pivot is?

Rotation creates exactly one 'break point' where a smaller value follows a larger one. Any range that doesn't cross it is in ascending order. The break point can fall in at most one half, so the other half is always fully sorted.

For a rotated sorted array that may contain duplicate values (e.g. `[3,3,1,3]`), why can the 'which half is sorted' check fail, and what does that do to worst-case time complexity?

If arr[low] === arr[mid] === arr[high], you can't tell which half is ordered. The usual fix is to shrink the range by one (low++ or high--) and try again. With nearly all-identical values, this degrades to O(n), since it may discard only one element per step.

How would you find the minimum element in a rotated sorted array (no duplicates) using binary search?

Compare arr[mid] with arr[high]. If arr[mid] > arr[high], the rotation point (and the minimum) is to the right, so low = mid + 1. Otherwise the minimum is at mid or to its left, so high = mid (not mid - 1, since mid could be the answer). The range keeps halving: O(log n).

You have a fully sorted 2D matrix where every row is sorted left-to-right and the first element of each row is greater than the last element of the previous row. How would you binary search it in O(log(m·n))?

Treat it as one flattened array of length mn, without copying. Map a flat index i to `(row, col) = (Math.floor(i / cols), i % cols)`, compare `matrix[row][col]` with the target, and narrow `low`/`high` as in 1D binary search. With mn elements, that's O(log(mn)) steps.

A different, more common kind of sorted 2D matrix has every row sorted left-to-right *and* every column sorted top-to-bottom, but rows aren't necessarily continuous with each other. Why doesn't the flattened-1D binary search work here, and what O(m+n) approach does?

Rows don't continue where the previous one ended, so the flattened order isn't globally sorted and halving breaks. Instead, start at the top-right corner: move left if the value is bigger than the target (dropping that column), move down if smaller (dropping that row), stop if equal. Each step drops a row or column, so at most m + n steps: O(m+n), much better than checking every cell.

What's the recursive-versus-iterative tradeoff for implementing binary search, in terms of space?

Iterative uses a few fixed variables (low, high, mid): O(1) extra space. Recursive adds a stack frame per halving, about log₂(n) of them: O(log n) extra space.

How would you find the square root of a non-negative number to some precision using binary search, given that the input isn't a discrete sorted array?

Search the range of possible answers. Set low = 0 and high = n (or a known upper bound), check whether mid * mid is below, above or close enough to n, and narrow the range. Stop when high - low is below the desired precision. This is 'binary search on the answer'.

What is 'binary search on the answer,' and what property must the answer space have for it to apply, even with no literal sorted array to search?

It applies halving to a range of candidate answers. You need a cheap check for 'is this candidate feasible?', and feasibility must be monotonic: once a value works, every value on one side of it works too. That yes/no boundary lets you discard half the candidates per check, like a sorted array.

Give an example of a problem solved with 'binary search on the answer' that has nothing to do with searching an array.

'Find the minimum eating speed k to finish all banana piles within h hours.' Binary search k from 1 to the largest pile. For each candidate, check in O(n) whether that speed finishes in time; this is monotonic, since if k works, every larger k works. Total: O(n log(max pile size)), instead of trying every speed.

What is exponential (galloping) search, and when is it more appropriate than plain binary search?

Use it when the array's size is unknown or effectively unbounded. Check index 1, then double (2, 4, 8, 16...) until the value is >= the target or you pass the end. Then binary search inside that last range. It finds a target at position p in O(log p), without knowing the length upfront.

What is ternary search, and why doesn't it beat binary search for simply finding a value in a sorted array?

It splits the range into three parts with two midpoints, discarding a third per step. Its depth is O(log₃ n), fewer levels than O(log₂ n), but each level makes two comparisons instead of one. Total comparisons are about the same order (often slightly worse), so it gives no asymptotic gain for plain search. It's mainly used to find the peak of a unimodal function.

Why does binary search silently give a wrong answer on unsorted data instead of erroring out?

It assumes that if the middle is too small, everything to its left is too (and the reverse), which only sorting guarantees. On unsorted data it still runs and returns an index or -1 with no way to detect the problem. It may report 'not found' for a present value, or return the wrong index.

Compare a hash table lookup to binary search for finding a value — when would you prefer O(log n) binary search over O(1) average hash table lookup?

Prefer binary search on a sorted array when you also need range queries, min/max or ordered iteration, which a hash table can't do efficiently. For exact lookups only, the hash table's O(1) average beats O(log n).

If you only need to perform a single search on data that isn't already sorted, is it worth sorting the array first to enable binary search?

No. Sorting is O(n log n) plus O(log n) for the search, worse than one O(n) scan. Sorting only pays off when you search the same data many times.

What's the time complexity of finding both the first and last position of a target value in a sorted array with duplicates, using two separate binary searches?

O(log n). Each search (leftmost and rightmost) is O(log n), and two of them is still O(log n).

What is the relationship between binary search and a binary search tree (BST)?

A BST applies the same halving idea (left if smaller, right if larger) to a dynamic linked structure. A balanced BST gives O(log n) search and insertion/deletion. A sorted array gives O(log n) search but O(n) insertion, since later elements must shift.

Trace a binary search for `target = 2` on `[1, 2, 4, 6, 8, 10]` (indices 0-5), reporting every `low`, `high`, and `mid` along the way.

low=0, high=5: mid=2, arr[2]=4 > 2, so high = 1. low=0, high=1: mid=0, arr[0]=1 < 2, so low = 1. low=1, high=1: mid=1, arr[1]=2 === target. Found at index 1.

What happens if you accidentally write `high = mid` instead of `high = mid - 1` in the standard `while (low <= high)` template, when the target is smaller than `arr[mid]`?

mid was already ruled out, but it stays in the range and can be checked again. Once low and high are adjacent or equal, mid can keep landing on the same index and the loop never ends. Exclude the checked mid on both sides.

What's the difference in `mid` calculation risk between `Math.floor((low + high) / 2)` and using bitwise `(low + high) >> 1` in JavaScript for very large arrays?

Math.floor works on regular doubles, exact for integers up to 2^53, far beyond any realistic array. >> first converts to 32-bit signed integers, so if low + high exceeds about 2^31 it silently wraps and gives the wrong midpoint. Rare, but a real trap.

How would you find a 'peak element' in an array (one greater than both its neighbors) using a binary-search-like approach, even though the array isn't sorted?

Compare arr[mid] with arr[mid + 1]. If arr[mid] < arr[mid + 1], values are still climbing, so a peak exists to the right; search the right half. Otherwise a peak is at mid or to its left; search the left half including mid. Each comparison shows which side must contain a peak, so you discard half per step: O(log n).

Why is it important that binary search's loop always makes forward progress, and what's a bug pattern that violates this?

If low/high don't shrink on some pass, the loop can run forever. A common bug: mid = Math.floor((low + high) / 2) with low = mid (instead of mid + 1). With low=3, high=4, mid is 3, so low = mid changes nothing and the loop repeats forever.

Scenario: you're building an autocomplete feature backed by a large sorted list of terms, and need 'all terms that start with prefix P.' How would binary search help, beyond just finding one exact match?

Run two binary searches: one for the leftmost term >= P (start of the range), and one for the leftmost term >= the next prefix after P (e.g. P with its last character incremented), the end of the range. Everything in between starts with P. Both are O(log n), so the range is found without a linear scan.

What's the time complexity of binary search in terms of the number of comparisons, precisely, and how does that relate to the O(log n) Big-O statement?

At most ⌊log₂(n)⌋ + 1 comparisons in the worst case. O(log n) is the same growth rate without the exact constant and base; changing a logarithm's base only scales it by a constant, which Big O ignores.

Why does binary search's advantage over linear search grow more dramatic as the input size increases, rather than staying at a fixed multiple?

Doubling the input doubles linear search's worst case but adds only one comparison to binary search. So the ratio keeps growing: about 1,000 vs. 10 comparisons at 1,000 items, but about 1,000,000,000 vs. 30 at 1,000,000,000 items.

Does binary search still work correctly on an array sorted in descending order?

Not with the standard ascending logic, which needs to know which side holds smaller values. Flip the comparisons (go left when arr[mid] is too small, right when too large) and it works in O(log n). Unmodified ascending logic on descending data gives wrong results, like running it on unsorted data.