First Bad Version
Find the first defective product version using binary search on a boolean API while minimizing calls and preventing integer overflow.
01The problem
You are a product manager leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
| Input | Output | Why |
|---|---|---|
n = 5, bad = 4 | 4 | Versions 1–3 are good; version 4 is the first bad one |
n = 1, bad = 1 | 1 | Only one version exists, and it is bad |
n = 2, bad = 2 | 2 | Version 1 is good; version 2 is bad |
Constraints: 1 ≤ bad ≤ n ≤ 2³¹ − 1.
02How to spot it
- The sequence of versions evaluated by
isBadVersionforms a monotonic boolean array:[false, false, ..., false, true, true, ..., true]. - We need to find the first true occurrence with the minimum number of API calls.
ncan reach 2³¹ − 1, making linear inspection completely impossible (up to 2 billion calls).
So: binary search on a boolean condition (lower bound).
03Pseudocode
lo = 1 ; hi = n
while lo < hi:
mid = lo + (hi - lo) / 2
if isBad(mid): hi = mid
else: lo = mid + 1
return lo- Versions read: good, good, ..., bad, bad.
- If
midis bad, the earliest failure is atmidor to its left:hi = mid. - If
midis good, the earliest failure must be strictly to the right:lo = mid + 1.
04Watch it work
Start search for the first defective version in range [1 .. 5].
Pseudocode
- lo = 1 ; hi = n
- while lo < hi:
- mid = lo + (hi - lo) / 2
- if isBad(mid): hi = mid
- else: lo = mid + 1
- return lo
Variables
- lo
- 1
- hi
- 5
- n
- 5
- targetBad
- 4
05Step-by-step dry run
- 11021324354lohi
Start search for the first defective version in range [1 .. 5].
lo = 1hi = 5n = 5targetBad = 4
- 21021324354lomidhi
Test version 3 with isBadVersion(3): result is GOOD.
lo = 1hi = 5mid = 3isBad = false
- 31021324354lohi
Version 3 is GOOD: the first bad version must be after 3. Set lo = 4.
lo = 4hi = 5
- 41021324354lomidhi
Test version 4 with isBadVersion(4): result is BAD.
lo = 4hi = 5mid = 4isBad = true
- 51021324354lohi
Version 4 is BAD: the first bad version must be 4 or earlier. Set hi = 4.
lo = 4hi = 4
- 61021324354firstBad
Search converged: lo = hi = 4. The first bad version is 4.
result = 4
06Java solution
public class FirstBadVersion {
static int badVersion = 4;
static boolean isBadVersion(int version) {
return version >= badVersion;
}
public static int firstBadVersion(int n) {
int lo = 1, hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2; // (lo + hi) / 2 can overflow
if (isBadVersion(mid)) hi = mid; // first bad is mid or earlier
else lo = mid + 1; // first bad is after mid
}
return lo;
}
public static void main(String[] args) {
badVersion = 4;
System.out.println(firstBadVersion(5));
badVersion = 1;
System.out.println(firstBadVersion(1));
badVersion = 2;
System.out.println(firstBadVersion(2));
}
}4 1 2
Tricky lines, decoded
lo + (hi - lo) / 2: Whenn = 2,126,753,390, addinglo + hiexceedsInteger.MAX_VALUEand overflows to a negative integer, causing an infinite loop.hi = mid: Ifmidis bad, it might itself be the very first bad version. Settinghi = mid - 1would incorrectly discard it.
07Why it works
The version status follows a step function: once a version is bad, every subsequent version is also bad. Testing the midpoint tells us which side of the boundary we are on. By discarding the good prefix when mid is good, and keeping mid as the upper bound when mid is bad, the search interval [lo, hi] always encapsulates the first bad version. When lo meets hi, the exact transition point is isolated.
Invariant: The first bad version always lies within [lo, hi].
08Time and space
- Time: O(log n). Even when
n = 2³¹ − 1, at most 31 API calls are made. - Space: O(1). Only two pointer variables are used.
09Edge cases
| Input | Output | Why it matters |
|---|---|---|
n = 1, bad = 1 | 1 | Single version, immediately bad |
n = 2, bad = 1 | 1 | First version in a pair is bad |
n = 2, bad = 2 | 2 | Last version in a pair is bad |
n = 10, bad = 10 | 10 | Only the very last version is bad |
n = 2126753390, bad = 1702766719 | 1702766719 | Huge values testing 32-bit integer overflow |
10Common mistakes
- Using
(lo + hi) / 2. Whenloandhiare large, this causes a 32-bit signed overflow into negative territory. - Writing
hi = mid - 1whenmidis bad. Ifmidhappens to be the first bad version, decrementinghieliminates the answer completely. - Calling the API twice per iteration. Writing
if (isBadVersion(mid)) ... else if (!isBadVersion(mid))calls the expensive API redundantly. Test once per midpoint.
11Other approaches
| Approach | Time | Space | Use when |
|---|---|---|---|
| Linear scan | O(n) | O(1) | Never with large n |
| Binary search | O(log n) | O(1) | Default interview answer |
| Exponential + binary search | O(log b) | O(1) | If the bug is known to be very recent |
| Recursion | O(log n) | O(log n) | Stack frames waste memory |
12In the interview
- What if the API call is extremely slow (e.g., runs a 10-minute integration test suite)? Exponential search starting from recent commits can isolate an initial upper bound before switching to binary search.
- Generalization: Any question asking to find the boundary between
falseandtruewhere the predicate is monotonic can be solved with this exact template.
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why is it critical to write lo + (hi - lo) / 2 in First Bad Version?
2. If isBadVersion(mid) returns true, why do we set hi = mid instead of hi = mid - 1?
14Solve it yourself
Try it on LeetCode #278.