Binary search pattern for coding interviews

The binary search pattern applies whenever a yes/no question about a position or a candidate answer flips exactly once, from no to yes, as the position grows. Keep a range that must contain the answer, test the middle, discard the half that cannot hold it, and you need about log2(n) tests instead of n. Most interview variants reduce to one template: find the first value for which a test passes.

By Published 8 min read

The classic signal is a sorted array, but the more useful signal is monotonicity. If you can phrase the question as "is x big enough?" and every value larger than a big-enough value is also big enough, binary search finds the smallest big-enough value. That covers searching a sorted list, finding where a sequence of good builds turns bad, finding an integer square root, and choosing the smallest capacity, speed or time limit that makes a plan work. When an interviewer gives you a problem whose brute force tries every candidate answer from small to large, ask whether feasibility only ever improves as the candidate grows. If it does, you can skip most of the candidates.

Clues in a prompt that point to binary search
ClueWhat to search overTest
"The list is sorted"Indexesvalues[i] >= target
"From some point on, every item is X"Positionsis_x(i)
"Find the minimum capacity / speed / days so that..."Candidate answersplan_fits(candidate)
"Sorted, but rotated"IndexesCompare with the last element
"Find the largest x with f(x) <= limit"Candidate answersFirst x with f(x) > limit, minus one
Clues in a prompt that point to binary search. Scroll sideways on a small screen.

Template 1: exact match in a sorted array

Use this when you need the index of a value and any matching index will do. The range is inclusive on both ends, the loop runs while lo <= hi, and both ends move past mid because mid has already been ruled out.

def find_exact(values, target):
    lo, hi = 0, len(values) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if values[mid] == target:
            return mid
        if values[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1
Exact match: returns an index of target, or -1.

Template 2: first position where a test passes

This is the template to memorize, because nearly every other variant is an instance of it. Search the half-open range [lo, hi). If the test passes at mid, the answer is mid or earlier, so hi = mid. If it fails, the answer is after mid, so lo = mid + 1. When the loop ends, lo is the first passing position, or hi if nothing passes. With duplicates in a sorted list, the test values[i] >= target gives the leftmost position where target could be inserted, which is what Python's bisect_left returns.

def first_true(lo, hi, ok):
    # smallest x in [lo, hi) with ok(x) True; hi if none.
    # ok must be False...False True...True over the range.
    while lo < hi:
        mid = (lo + hi) // 2
        if ok(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

def lower_bound(values, target):
    return first_true(0, len(values), lambda i: values[i] >= target)
Python: the general boundary search and a lower bound built on it.
function firstTrue(lo, hi, ok) {
  while (lo < hi) {
    const mid = lo + Math.floor((hi - lo) / 2);
    if (ok(mid)) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}

function lowerBound(values, target) {
  return firstTrue(0, values.length, i => values[i] >= target);
}
JavaScript: the same template; the midpoint form avoids overflow habits carrying into other languages.

The last position where something holds is the mirror image: find the first position where it stops holding, then subtract one. The integer square root of n, for example, is the first r with r × r > n, minus one.

Template 3: binary search over possible answers

Here is an example written for this page. A book has chapters of known lengths in a fixed order, and k readers will each take a run of consecutive chapters. What is the smallest possible maximum number of pages any one reader gets? Trying every way to split is exponential. But for a given page cap, a greedy pass answers "can k readers manage with at most this many pages each?" in O(n): give chapters to the current reader until the next one would exceed the cap, then start a new reader. A bigger cap never needs more readers, so the test flips once, and Template 2 finds the smallest cap that fits. The lowest cap worth trying is the longest chapter; the highest is the whole book.

def smallest_max_load(pages, readers):
    def fits(cap):
        used, load = 1, 0
        for p in pages:
            if load + p > cap:
                used, load = used + 1, 0
            load += p
        return used <= readers
    return first_true(max(pages), sum(pages) + 1, fits)
Search over answers: O(n log S) where S is the total number of pages.
function smallestMaxLoad(pages, readers) {
  const fits = cap => {
    let used = 1, load = 0;
    for (const p of pages) {
      if (load + p > cap) { used++; load = 0; }
      load += p;
    }
    return used <= readers;
  };
  const total = pages.reduce((a, b) => a + b, 0);
  return firstTrue(Math.max(...pages), total + 1, fits);
}
JavaScript version, reusing firstTrue.

Chapters [6, 3, 8, 2, 4, 7] with three readers give 11: the readers take 6 + 3 = 9, 8 + 2 = 10 and 4 + 7 = 11, and no cap of 10 or less can be covered by three people.

A variant: sorted, then rotated

If a sorted list of distinct values was rotated, so it looks like [61, 75, 88, 14, 29, 40], the smallest value sits right after the drop. Compare the middle with the last element. If the middle is larger, the drop is to its right; otherwise the middle could be the minimum, so keep it.

def rotated_min(values):
    lo, hi = 0, len(values) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if values[mid] > values[hi]:
            lo = mid + 1   # the drop is to the right of mid
        else:
            hi = mid       # mid could be the minimum
    return values[lo]
Minimum of a rotated sorted list of distinct values, O(log n).

Example problems to practice

  • [First Bad Version](/coding-problems/first-bad-version). Template 2 with an expensive check instead of an array. The best first problem for this pattern.
  • Insert position in a sorted list. Return where a value would go to keep the list sorted: exactly lower_bound above.
  • First and last position of a value. Two boundary searches: first index with value >= target, and first index with value > target, minus one.
  • Integer square root without a math library. Search answers from 0 to n + 1 for the first r with r × r > n.
  • Smallest working speed or capacity. Any "minimum rate to finish within a deadline" question is Template 3 with a different feasibility test.
  • Find a peak. In a list where neighbors differ, compare mid with mid + 1 and move toward the larger side; a peak must exist there.

Complexity

Typical costs. n is the list length; R is the size of the answer range.
UseTimeExtra space
Exact match or lower bound in a sorted listO(log n)O(1)
Boundary search with an O(1) testO(log R)O(1)
Search over answers with an O(n) feasibility passO(n log R)O(1) beyond the input
Rotated list minimum (distinct values)O(log n)O(1)
Typical costs. n is the list length; R is the size of the answer range.. Scroll sideways on a small screen.

Common mistakes

  • Mixing templates. Using lo <= hi together with hi = mid can loop forever. Pair lo <= hi with mid ± 1, and lo < hi with hi = mid.
  • The wrong initial range. For lower bound, hi must be len(values), not len - 1, or a target larger than everything has nowhere to go.
  • A test that is not monotone. If feasibility can flip back, binary search silently returns a wrong answer. Say why the test only improves.
  • Overflow in the midpoint in Java, C++ or C#: write lo + (hi - lo) / 2.
  • Rotated lists with duplicates. When values[mid] equals values[hi], you cannot tell which side the drop is on; shrink hi by one, which makes the worst case O(n).

How to explain it out loud

Fictional example

Turning a brute force into a search over answers
Candidate
I could try every page cap from the longest chapter upward and stop at the first that works. That is correct but slow when the book is long.
Candidate
If a cap works, any bigger cap works too, because each reader can only take more. So feasibility is false and then true, and I can binary search for the first true cap.
Candidate
Each check is a greedy pass, O(n), and I do about log of the total pages checks, so O(n log S) overall.

Binary search pairs well with the two pointers pattern, which handles many sorted-array problems without any halving, and with the heap and priority queue pattern when you need the k-th smallest of many lists. The full set is on the coding problems hub.

Practicing with Natively

Natively, a desktop app for Mac and Windows, can read a practice problem from a screenshot and suggest whether a search over answers fits and what the feasibility test would be, which is a good check after you have attempted it yourself. Mock rounds are transcribed and saved, so you can see whether you justified why the test is monotone. More on the AI interview assistant.

Questions people ask

How do you know when to use binary search?

When the data is sorted, or when a yes/no test about a position or candidate answer is false up to some point and true from then on. If larger candidates can only make the test pass more easily, you can binary search for the first one that passes.

What is binary search on the answer?

Searching over possible answers, such as capacities or speeds, instead of array indexes. You write a feasibility check for one candidate and binary search for the smallest candidate that passes.

Should the loop be while lo < hi or while lo <= hi?

Use lo <= hi with mid plus or minus one for an exact match, and lo < hi with hi = mid for a first-position search. Mixing the two causes infinite loops or skipped answers.

What is the time complexity of binary search?

O(log n) tests for a range of size n. When each test is an O(n) feasibility pass, as in searches over answers, the total is O(n log R) for an answer range of size R.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP