Binary search solution explained
Binary search finds a value in a sorted array by checking the middle element and throwing away the half that cannot contain the target, so each step halves the remaining range and the search takes O(log n) time with O(1) extra space. The hard part is not the idea but the boundaries: decide whether your range is closed or half-open, keep that invariant in every update, and the loop ends correctly.
By Evin JohnPublished 8 min read
The task, restated
You are handed a list of distinct integers sorted from smallest to largest and one more integer, the target. Report the index where the target sits, counting from 0, or -1 if it is not in the list. The list is sorted, and the expected solution must use that fact: the usual requirement is a running time of O(log n).
| Sorted list | Target | Result | Note |
|---|---|---|---|
| [2, 5, 8, 12, 19, 23] | 12 | 3 | Found after two halvings |
| [2, 5, 8, 12, 19, 23] | 7 | -1 | Would sit between 5 and 8 |
| [2, 5, 8, 12, 19, 23] | 2 | 0 | The first element |
| [6] | 6 | 0 | One element, found |
| [] | 4 | -1 | Empty list |
Clarify two things before coding. Can values repeat, and if so which copy should you return, any, the first or the last? And is the answer the position, a yes or no, or the place the target would be inserted? Each of those is a small change to the same loop, and asking shows you know the variants exist.
Why such a simple problem gets asked
Binary search looks trivial and is easy to get subtly wrong. An interviewer can watch for an infinite loop on a two-element range, a missed last element, or an index that runs off the end. It also opens the door to the whole family of harder questions: searching a rotated list, finding a boundary, or searching over possible answers instead of over an array. A candidate who can state the loop invariant clearly usually handles those follow-ups without trouble.
Baseline: check every element
Walk the list from the left and stop when you see the target. That is O(n) time and O(1) space, and it ignores the ordering entirely. Mention it in one sentence, then point out that sorting lets you rule out half the list with a single comparison.
def find_linear(values, goal):
for i, v in enumerate(values):
if v == goal:
return i
return -1The halving loop
Keep two indexes, low and high, that bracket the part of the list where the target could still be. With the closed convention, both ends are included, so the range is empty once low passes high. Look at the middle index. If the value there is the target, you are done. If it is smaller, the target can only be to the right, so move low to one past the middle. If it is larger, move high to one before the middle. Every step removes the middle and at least half of what is left.
def find_sorted(values, goal):
low, high = 0, len(values) - 1
while low <= high:
mid = low + (high - low) // 2
if values[mid] == goal:
return mid
if values[mid] < goal:
low = mid + 1
else:
high = mid - 1
return -1function findSorted(values, goal) {
let low = 0;
let high = values.length - 1;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
if (values[mid] === goal) return mid;
if (values[mid] < goal) low = mid + 1;
else high = mid - 1;
}
return -1;
}Writing the midpoint as low + (high - low) / 2 rather than (low + high) / 2 avoids integer overflow in languages with fixed-width integers, such as C++, Java and Go, when both indexes are large. Python integers do not overflow and JavaScript numbers are exact well beyond any array length, so it matters less there, but interviewers like to hear that you know why the habit exists.
The invariant that keeps you out of trouble
State it out loud: if the target is in the list at all, it lies between low and high, both included. The initial values make it true. Each update keeps it true, because you only discard positions you have just proved cannot hold the target. The loop stops when the range is empty, and at that point the invariant says the target is nowhere, so -1 is correct. Off-by-one bugs come from mixing conventions, such as using high = len(values) with while low <= high, which reads past the end, or high = mid with a closed range, which can loop forever.
| Convention | Start | Loop test | Move right | Move left |
|---|---|---|---|---|
| Closed [low, high] | high = n - 1 | low <= high | low = mid + 1 | high = mid - 1 |
| Half-open [low, high) | high = n | low < high | low = mid + 1 | high = mid |
The variant you will use most: first position at least x
Many problems do not ask whether a value exists but where a boundary is: the first index whose value is at least x, the first day a condition becomes true, the smallest speed that is fast enough. Write that with the half-open convention. The answer always lies in [low, high], the loop narrows that range until it has one candidate left, and it never needs an equality check. With repeated values it returns the leftmost copy, and when every value is smaller than x it returns n, the position where x would be inserted.
def first_at_least(values, goal):
low, high = 0, len(values) # answer lies in [low, high]
while low < high:
mid = (low + high) // 2
if values[mid] < goal:
low = mid + 1
else:
high = mid
return lowOn [1, 3, 3, 3, 7], asking for 3 returns 1, the first copy, and asking for 4 returns 4, the slot just before the 7. Python's standard library has this as bisect.bisect_left, and C++ has std::lower_bound. Using them is usually fine once you have shown you can write the loop yourself.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Linear scan | O(n) | O(1) |
| Iterative binary search | O(log n) | O(1) |
| Recursive binary search | O(log n) | O(log n) for the call stack |
| First position at least x | O(log n) | O(1) |
Inputs to test
- Empty list: the loop never runs and the answer is -1.
- One element, equal to the target and not equal to it.
- Target at index 0 and at the last index, the classic places for an off-by-one.
- Target smaller than everything and larger than everything.
- Two elements, which is where a wrong midpoint or update most often loops forever.
- Repeated values, if the question allows them and asks for the first or last copy.
Common mistakes
- Writing
while low < highwith a closed range, which skips checking the last remaining element. - Setting
low = midinstead ofmid + 1, which can stall forever whenhigh = low + 1. - Using
/in JavaScript or Python 3 without flooring, producing a fractional index. - Running binary search on data that is not sorted, or sorted in the other direction, without saying so.
- Returning the wrong thing when the target is missing: -1, the insertion point and None are all different answers.
How to explain it out loud
Fictional example
- Candidate
- The list is sorted, so a single comparison with the middle tells me which half can still contain the target. That gives log n steps instead of n.
- Candidate
- I'll use a closed range. The rule I'm keeping is that if the target exists, it's between low and high inclusive. When the middle is too small, I move low past it; when it's too big, I move high below it.
- Interviewer
- What if there are duplicates and I want the first one?
- Candidate
- Then I switch to a half-open range and never stop on equality: if the middle value is at least the target, I keep it as a candidate by setting high to mid. The loop ends on the leftmost position.
Where binary search goes next
Search a 2D Matrix runs the same loop over a grid by treating it as one long list. Koko Eating Bananas searches over possible answers rather than an array, using the first-position variant above. Find Minimum in Rotated Sorted Array and Search in Rotated Sorted Array show how to keep halving when only part of the list is in order. Every walkthrough is grouped by pattern on the coding problems hub.
Practicing binary search with Natively
Since the bugs here are boundary bugs, the most useful practice is narrating your invariant and then tracing a two-element list by voice. Natively, which runs on Mac and Windows, writes a transcript of that practice round so you can check afterward whether you named the convention before coding. In practice it can also read a variant from a screenshot and suggest how the loop should change. More on the AI assistant for coding interviews page.
Questions people ask
How does binary search work?
On a sorted list, compare the target with the middle element. If they match you are done; otherwise discard the half that cannot contain the target and repeat on the other half until the range is empty.
What is the time complexity of binary search?
O(log n) time, because each step halves the remaining range, and O(1) extra space for the iterative version. A recursive version uses O(log n) stack space.
Should I use while low <= high or while low < high?
Either, as long as the rest of the loop matches. A closed range [low, high] uses low <= high with high = mid - 1; a half-open range [low, high) uses low < high with high = mid.
How do I find the first occurrence with binary search?
Use the half-open loop that keeps mid as a candidate whenever its value is at least the target. It ends on the leftmost such position, like bisect_left in Python or lower_bound in C++.
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.
