We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy binary search problem, graded against 6 test cases (3 of them hidden).
Halving a search space each step - on sorted arrays, and on answers themselves.
Reach for it when you see: A sorted input, or a monotonic "is this value feasible?" predicate you can binary search over.
More Binary Searchproblems →This is the canonical example of binary searching a monotonic predicate. There is no sorted array to look at - only a yes/no test - but the answers form the pattern `false false ... false true ... true`, and that is all binary search needs.
Search for the boundary: while `lo < hi`, test the midpoint. If it is bad, the first bad version is at `mid` or earlier, so set `hi = mid` - crucially not `mid - 1`, which could step over the answer. If it is good, the boundary is strictly after, so `lo = mid + 1`. When they meet, that is the first bad version.
Overflow is a real hazard here rather than a theoretical one, since `n` can be 2^31 - 1: `(lo + hi) / 2` overflows a 32-bit int in the very first iteration for large ranges. Use `lo + (hi - lo) / 2`. (JavaScript and Python are immune, but the interviewer will usually ask.)
The general lesson transfers widely: any problem where a boolean condition flips exactly once across a range - minimum capacity to ship in D days, smallest divisor under a threshold - is a binary search, even when nothing is sorted.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
These apply to the pattern as a whole, not just this problem.