First Bad Version solution explained
First Bad Version is solved with binary search on a boundary: keep a range that must contain the first bad version, test the middle, and move the upper end down to the middle when it is bad or the lower end past the middle when it is good. It needs about log2(n) checks instead of n, and the only traps are the loop condition and computing the midpoint without overflow.
By Evin JohnPublished 8 min read
The problem in plain words
A team shipped versions numbered 1 through n, one after another. At some point a bug slipped in, and because each version builds on the one before, every version from that point onward is also broken. You have a function that takes a version number and answers true if that version is broken. Each call is expensive, for example a full test run, so the goal is to find the first broken version while calling the function as few times as possible. You may assume at least one version is broken.
| n | Versions | Answer | Note |
|---|---|---|---|
| 6 | G G G B B B | 4 | The break is in the middle |
| 5 | B B B B B | 1 | Every version is broken |
| 7 | G G G G G G B | 7 | Only the last one is broken |
| 1 | B | 1 | A single version, which must be the bad one |
Questions to ask first: is it guaranteed that some version is bad, and what should happen if not? How large can n be? (If it can approach the largest 32-bit integer, the midpoint formula matters.) Is the check deterministic, or can a flaky test give different answers for the same version?
Why it is asked
The problem strips binary search down to its most useful form. There is no array and no target value, just a yes/no test that is false for a while and then true forever. That shape, a monotone predicate, is behind a large share of binary search questions, from finding a square root to choosing the smallest machine size that meets a deadline. Interviewers use it to see whether you can write the loop without off-by-one errors and explain why it terminates. It is also a realistic task: the git bisect command applies the same halving idea to a commit history.
Brute force: check every version in order
Start at version 1 and call the check on each version until one comes back broken. It is correct and simple, and it uses up to n calls, which is O(n) time. If each check is a twenty-minute test run and n is a few thousand, that is weeks. Mention it in one sentence and move on.
def first_bad_linear(n, is_bad):
for v in range(1, n + 1):
if is_bad(v):
return v
return -1 # only if the guarantee is brokenOptimal approach: binary search on the boundary
The versions form a row of goods followed by a row of bads, so one check on any version tells you which side of the boundary it is on. Keep two numbers, lo and hi, with the promise that the first bad version is somewhere in [lo, hi]. Start with lo = 1 and hi = n. Check the middle. If the middle is bad, the answer is the middle or something before it, so set hi = mid; you must keep mid in the range because it might be the answer. If the middle is good, the answer is strictly after it, so set lo = mid + 1. Stop when lo equals hi: the range has one version left and it is the answer.
This loop always shrinks the range, because mid is strictly less than hi whenever lo < hi, so both branches make progress. It makes at most about log2(n) calls: for a million versions, around twenty.
def first_bad(n, is_bad):
lo, hi = 1, n
while lo < hi:
mid = lo + (hi - lo) // 2
if is_bad(mid):
hi = mid # mid might be the first bad one
else:
lo = mid + 1 # first bad is strictly after mid
return lofunction firstBad(n, isBad) {
let lo = 1, hi = n;
while (lo < hi) {
const mid = lo + Math.floor((hi - lo) / 2);
if (isBad(mid)) hi = mid;
else lo = mid + 1;
}
return lo;
}int firstBad(int n, const std::function<bool(int)>& isBad) {
int lo = 1, hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (isBad(mid)) hi = mid; else lo = mid + 1;
}
return lo;
}Complexity
| Approach | Calls to the check | Extra space |
|---|---|---|
| Linear scan | Up to n, O(n) | O(1) |
| Binary search on the boundary | About log2(n), O(log n) | O(1) |
| Recursive binary search | O(log n) | O(log n) call stack |
Edge cases to test
- n = 1: the loop never runs and the function returns 1.
- The first version is bad: hi keeps moving down until it reaches 1.
- Only the last version is bad: lo keeps moving up until it reaches n.
- A very large n, near the 32-bit limit: the overflow-safe midpoint matters in Java, C++ and C#. Python integers and JavaScript numbers (exact up to 2^53) are not affected at that size.
- No bad version at all, if the interviewer drops the guarantee: the loop returns n, so add one final check of n and return a sentinel if it is good.
Mistakes that cost points
- Setting hi = mid - 1 when mid is bad. That can skip the answer, since mid itself may be the first bad version.
- Writing while lo <= hi with hi = mid. When lo equals hi and that version is bad, nothing changes and the loop never ends.
- Using (lo + hi) / 2 in a language with fixed-size integers.
- Calling the check twice per step, once on mid and once on mid - 1, to test whether mid is "the" boundary. It still works but doubles the calls, which is the thing the problem asks you to minimize.
- Returning mid from inside the loop instead of lo after it. The template ends with a single candidate; trust it.
How to explain it out loud
Fictional example
- Candidate
- Checking versions in order works but costs n calls. The versions are all good and then all bad, so each check tells me which side of the switch I am on. That is a binary search for a boundary.
- Candidate
- I keep lo and hi so the first bad version is always inside [lo, hi]. If mid is bad, the answer is mid or earlier, so hi becomes mid. If mid is good, the answer is after it, so lo becomes mid plus one. When they meet, that is the answer.
- Candidate
- Each step halves the range, so about log n calls and constant space. I compute mid as lo plus half the gap so it cannot overflow. Tracing n = 6 with the first bad at 4: mid 3 is good, lo = 4; mid 5 is bad, hi = 5; mid 4 is bad, hi = 4; they meet at 4.
Follow-ups and related problems
- Find the boundary in a sorted array instead of a function. The same loop finds the first index whose value is at least some target, which is what bisect_left in Python does.
- The check is flaky. Binary search assumes a clean switch; discuss retrying a check, or confirming the final answer and its neighbor.
- You can test several versions in parallel. Split the range into k parts per round instead of two, which cuts the number of rounds to about log base k of n.
- Smallest value that satisfies a condition. Replace the version check with any yes/no test that flips once, such as "can this batch finish in time with x workers?". The binary search pattern guide covers that template.
Binary search is one of several ways to avoid rescanning work; the two pointers pattern is another, and the sorted follow-up to Two Sum uses it. All walkthroughs are on the coding problems hub.
Practice it with Natively
When you practice, Natively can read a problem like this from a screenshot and sketch an approach in its overlay, which is useful for checking your loop invariant after you have written your own. It also transcribes mock rounds on your Mac or Windows computer, so you can hear whether you explained why the loop ends. See the AI assistant for coding interviews.
Questions people ask
What is the optimal solution to First Bad Version?
Binary search on the boundary. Keep lo and hi around the answer; if the middle version is bad set hi to mid, otherwise set lo to mid plus one, and stop when they meet. It uses about log2(n) checks and constant space.
Why is hi set to mid and not mid minus one?
Because a bad middle version might itself be the first bad one. Setting hi to mid keeps it in the range; the loop condition lo < hi still guarantees progress.
Why use lo + (hi - lo) / 2 for the midpoint?
In languages with fixed-size integers, lo + hi can overflow when n is close to the maximum int. Adding half the gap to lo gives the same midpoint without overflow.
What is the time complexity of First Bad Version?
O(log n) calls to the check with binary search and O(1) extra space, compared with O(n) calls for checking versions in order.
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.
