Skip to content

Binary Search: First True, Answer Spaces and Edge Cases

Learn binary search as a hunt for the first true value of a monotone predicate, including searching answer ranges and getting the boundaries right.

12 min readTime: O(n log R) for the example; O(log n) for plain array searchMemory: O(1)AlgorithmsBinary search

Most people learn binary search as a way to find a value in a sorted array. Interviews rarely ask exactly that. They ask where a value would be inserted, how many elements fall below a threshold, or what the smallest setting is that makes some plan work. All three are the same algorithm in different clothes. This guide treats binary search as one idea: find the boundary where a yes/no condition switches from false to true. Once you see it that way, you can search the indices of an array and you can also search a range of possible answers. You will also learn how to set the edges so the loop always ends and returns the right thing.

The intuition

The picture to keep in your head.

Picture a row of lights where every light on the left is off and every light on the right is on. You want the first light that is on. You can check any single light, but each check costs you. If you check the middle light and it is on, the first on-light is that one or something to its left, so the whole right half is settled. If it is off, the first on-light is strictly to the right. Each check halves what is left. With a million lights, about 20 checks are enough, because 2^20 is just over a million.

The row does not have to be an array. It only needs a predicate that is false for small inputs and true for large inputs, with exactly one switch. In a sorted array, a[i] >= x has that shape over indices. In a scheduling problem, "can we finish by minute T?" has that shape over T, because more time never hurts. Monotonicity is the only requirement. Sortedness is just one way to get it.

Searching the answer space means you never build the row. You pick a low bound that is surely too small or exactly right, and a high bound that is surely enough, then binary search over the numbers between them. You call the predicate on each candidate. Checking a candidate might take O(n), but you only do it about log(range) times.

Edges are where bugs live. Commit to one invariant and keep it: the answer always lies in [lo, hi], and hi is known to be true. When mid is true, set hi = mid, since mid could be the answer. When mid is false, set lo = mid + 1, since mid cannot be. The loop runs while lo < hi and ends with lo == hi pointing at the first true. Every iteration shrinks the interval, so it cannot loop forever.

Step by step

Small, safe steps, with the tests passing after each.

  1. Step 1: Phrase the question as a predicate

    Write a function ok(x) that returns true or false. For an array, x is an index and ok might be a[x] >= target. For an answer search, x is a candidate answer and ok asks whether that candidate is enough. Before you go further, convince yourself that once ok becomes true it stays true as x grows.

  2. Step 2: Choose bounds that bracket the answer

    Set lo to the smallest value that could be the answer. Set hi to a value where ok is guaranteed true. For arrays, hi = n works as a virtual position meaning past the end, which is true by convention. For answer spaces, find a cheap upper bound you can justify, such as the total load or the slowest case.

  3. Step 3: Take a midpoint that cannot overflow or stall

    Compute mid = lo + (hi - lo) / 2 with integer division. This rounds down, so mid < hi whenever lo < hi. That is exactly what you need for the update hi = mid to shrink the interval.

  4. Step 4: Update while keeping the invariant

    If ok(mid) is true, set hi = mid. The answer is mid or something before it. If ok(mid) is false, set lo = mid + 1. The answer is strictly after mid. Do not write lo = mid here. With a rounded-down mid, that can repeat the same interval forever.

  5. Step 5: Stop when the interval is a single point

    Loop while lo < hi. When the loop ends, lo == hi and that value is the first x where ok is true. For arrays with hi = n, a result of n means no element satisfied the predicate, so check for it before you index into the array.

  6. Step 6: Flip it for last-true questions

    If you want the last x where some property holds, search for the first x where it fails and subtract one. You could also round mid up and use lo = mid / hi = mid - 1. Pick one form and keep it, because mixing the two is the classic source of off-by-one errors.

What it costs

Time and memory, and why.

Time
O(n log R) for the example; O(log n) for plain array search
Memory
O(1)

Each iteration at least halves the interval [lo, hi], so the loop runs about log2 of the interval size before the interval is a single point. For an array that size is n. For an answer search it is the range R = hi - lo. Each iteration does one predicate call. Comparing one array element costs O(1). In the oven example below, the predicate loops over the n ovens, which gives O(n log R) overall. Only a few integer variables are stored, so extra space is constant.

A traced example

A small input, followed step by step.

The bakery Crumb & Co. has three ovens with batch times [3, 5, 7] minutes. Each oven bakes one batch at a time, back to back, and all ovens start at minute 0. What is the earliest minute T by which at least 10 batches are done? Batches done by T = floor(T/3) + floor(T/5) + floor(T/7).

  1. 1lo = 1, hi = 3 * 10 = 30The fastest oven alone bakes 10 batches in 30 minutes, so T = 30 is surely enough. The answer lies in [1, 30].
  2. 2mid = 15, done = 5 + 3 + 2 = 10 >= 10, so hi = 1515 works, so the answer is 15 or earlier. Keep 15 inside the interval.
  3. 3lo = 1, hi = 15, mid = 8, done = 2 + 1 + 1 = 4 < 10, so lo = 98 fails, and so does every minute before it. Discard 1 through 8.
  4. 4lo = 9, hi = 15, mid = 12, done = 4 + 2 + 1 = 7 < 10, so lo = 13Still short. The answer is strictly after 12.
  5. 5lo = 13, hi = 15, mid = 14, done = 4 + 2 + 2 = 8 < 10, so lo = 1514 falls two batches short, so the switch from false to true happens at 15.
  6. 6lo = 15, hi = 15, loop endsThe interval is a single point. It took four predicate calls to search 30 candidates.

Result: The earliest finishing minute is 15.

The code

The same solution in TypeScript, Python and PHP.

// Returns true if the ovens finish at least `target` batches within `minutes`.
function canFinish(batchTimes: number[], minutes: number, target: number): boolean {
  let done = 0;
  for (const t of batchTimes) {
    done += Math.floor(minutes / t);
    if (done >= target) return true; // stop early, avoids huge sums
  }
  return false;
}

// Smallest minute T such that canFinish(T) is true (first true of a monotone predicate).
function earliestFinish(batchTimes: number[], target: number): number {
  let lo = 1;
  let hi = Math.min(...batchTimes) * target; // fastest oven alone is always enough
  while (lo < hi) {
    const mid = lo + Math.floor((hi - lo) / 2);
    if (canFinish(batchTimes, mid, target)) {
      hi = mid; // mid works: answer is mid or earlier
    } else {
      lo = mid + 1; // mid fails: answer is strictly later
    }
  }
  return lo;
}

console.log(earliestFinish([3, 5, 7], 10)); // 15

Variants

Shapes the same idea takes.

  • Lower bound on a sorted array

    When: You need the first index whose value is at least x. Typical uses are insertion points, counting elements below x, and handling duplicates.

    Use the predicate a[i] >= x with lo = 0 and hi = n. The result is the insertion index, and it also equals the number of elements strictly less than x. With an upper bound (first a[i] > x) as well, the count of elements equal to x is upper minus lower. Each query costs O(log n), so you can sort once and answer many queries cheaply.

  • Last true / maximize a feasible value

    When: The question asks for the largest value that still works, such as the biggest minimum gap or the longest prefix that fits a budget.

    Here the predicate is true on the left and false on the right. Search for the first false and subtract one. Or round mid up with mid = lo + (hi - lo + 1) / 2 and use lo = mid on true, hi = mid - 1 on false. Rounding up is required, or the loop can stall when hi = lo + 1.

  • Binary search on real numbers

    When: The answer is continuous, such as a square root, a rate or a threshold ratio, and you need it to a given precision.

    There is no off-by-one with real numbers, but floating-point equality is unreliable. Run a fixed number of iterations instead, around 60 to 100 for doubles, and set lo = mid or hi = mid by the predicate. Return either end. Each iteration halves the error.

  • Rotated or partially ordered arrays

    When: The array was sorted and then rotated, or you are looking for a peak in an array that rises and then falls.

    The full array is not monotone, but a predicate on it can be. For the rotation point, test a[mid] <= a[n-1]. For a peak, test a[mid] > a[mid+1]. Find the right predicate and the usual first-true template takes care of the rest.

Common mistakes

What usually goes wrong and how to avoid it.

  • Avoid

    Writing lo = mid when the predicate is false, alongside a rounded-down mid.

    Better

    If mid failed, it cannot be the answer, so use lo = mid + 1. With lo = mid and mid rounding down, the interval [k, k+1] never shrinks and the loop runs forever.

  • Avoid

    Picking a hi that is not guaranteed to satisfy the predicate.

    Better

    Prove that hi works before searching, for example with the slowest single resource, the total sum, or n as a past-the-end index. If there may be no valid answer, check ok(hi) after the loop and handle that case.

  • Avoid

    Mixing inclusive and half-open interval styles in the same loop.

    Better

    Pick one invariant, such as the answer always being in [lo, hi] with hi true, and derive the loop condition and both updates from it. Do not copy the condition from one template and the updates from another.

  • Avoid

    Applying binary search to a predicate that is not monotone.

    Better

    Before coding, argue that if x works then x + 1 works as well. In the oven example, more minutes never means fewer batches. If that argument fails, binary search can return a wrong answer without any error.

  • Avoid

    Computing mid as (lo + hi) / 2 with fixed-width integers.

    Better

    Use lo + (hi - lo) / 2. In Java, C++ or Go, lo + hi can overflow on large ranges. Also cap running sums inside the predicate, as the early return in canFinish does.

  • Avoid

    Indexing the array with the result without checking for n.

    Better

    A lower bound returns n when every element is smaller than x. Check result < n before reading a[result].

How to recognise it

Clues in a problem statement that call for it.

  • The input is sorted, or you can sort it once, and you need a position, a count below a threshold, or the first or last occurrence.
  • The problem asks for the minimum value that is enough or the maximum value that still fits, such as capacity, speed, time or distance.
  • Checking one candidate answer is easy, often a greedy O(n) pass, but computing the answer directly is hard.
  • There is an obvious monotonicity: more of the resource never makes the task fail.
  • Constraints have answers up to around 10^9 or more while n is moderate, which suggests O(n log range).
  • The phrase "minimize the maximum" or "maximize the minimum" appears in the statement.
  • You need many queries on static data, and each query should cost O(log n) instead of O(n).

Common questions

Short answers to the usual doubts.

Why lo < hi instead of lo <= hi?

With the first-true template, hi always holds a known true value, and the loop's job is to shrink [lo, hi] to one point. Once lo == hi there is nothing left to decide. The lo <= hi form belongs to the classic exact-match search, which returns as soon as it finds the target and uses hi = mid - 1. Both forms work. Problems come from mixing pieces of the two.

How do I find a good upper bound when searching the answer space?

Look for a value that is trivially sufficient. That could be the sum of all work, the largest single item times the count, the worst-case time of the slowest worker, or one resource doing everything. The bound does not have to be tight. Doubling the range only adds one iteration.

Do I need the exact-match version at all?

Rarely. Run a lower bound for x, then check whether the index is less than n and a[index] == x. This handles duplicates correctly, since it returns the first occurrence, and you only have one template to remember.

How do I explain the complexity in an interview?

Say that each iteration halves the candidate range, so there are about log2(range) iterations, and each one calls the predicate once. Then give the predicate's cost. For an answer search with an O(n) check, the total is O(n log R), where R is the size of the answer range. Name R explicitly, since it is not n.

What if the predicate is true for the very first candidate?

The template handles that. Every true check moves hi down, and the loop ends with lo == hi == the initial lo. Just make sure the initial lo really is the smallest possible answer. In the oven example that is minute 1, not 0, since no batch can finish at minute 0.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.