DSA · Patterns, not puzzles
How does binary search work?
Short answer
Binary search halves a sorted search space each step, giving O(log n) time. The key is a consistent boundary rule and a correct midpoint calculation.
Binary search maintains a range of candidate indices. It checks the midpoint, then discards the half that cannot contain the answer. The hard part is not the idea; it is keeping the boundaries and loop condition consistent so the algorithm terminates and does not skip the answer.
function lowerBound(values, target) {
let left = 0;
let right = values.length;
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (values[mid] < target) left = mid + 1;
else right = mid;
}
return left;
}Avoiding the classic bugs
- Use left + Math.floor((right - left) / 2) to avoid overflow in fixed-width languages
- Decide whether the range is inclusive or half-open and stay consistent
- Make sure every branch shrinks the range
- For first or last occurrence, do not return immediately on a match
Binary search also applies to monotonic answer spaces, not just arrays. If a predicate is false up to some point and true afterwards, you can binary search for the boundary. That is the basis of problems such as minimum capacity or minimum speed.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How do you find the first and last occurrence of a value?
- 2What is binary search on the answer?
- 3Why use a half-open range?
- 4What happens if the array contains duplicates?
Say it in the interview
Binary search halves a sorted range each step by comparing the middle element with the target. I use a consistent half-open range so the loop ends cleanly and the answer is at left. For duplicates, I keep searching after a match to find the first or last occurrence. The same idea works on a monotonic predicate, which is how binary search on the answer works.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live DSA mock interview and get scored feedback on depth, clarity and confidence.