Walk me through how binary search works, what its prerequisite is, and one subtle bug people introduce when they compute the midpoint.

technical-conceptual · Junior level · software-engineering

What the interviewer is really asking

Tests whether the candidate can explain binary search's halving mechanic, knows the sorted-input prerequisite, and is aware of the classic integer-overflow midpoint bug and its fix.

What to say

What to avoid

Example answers

Strong: I keep two bounds, low and high. Each step I look at the middle element: if it equals the target I'm done, if the target is smaller I move high to mid-1, otherwise I move low to mid+1. Halving each step makes it O(log n) — a million-element sorted array is about 20 comparisons. The prerequisite is that the array is sorted, because the whole method depends on knowing which half the target must be in. The subtle bug I watch for is the midpoint: `(low + high) / 2` can overflow on large indices, so I write `low + (high - low) / 2` instead.

Weak: I look at the middle element and go left or right depending on the target — it's faster than checking everything. I don't think the array has to be sorted, you just split it in half each time.

Want questions matched to your role? Paste a job title, job description, or CV and get a personalized set, or go Pro to unlock the full bank.