First Bad Version (LeetCode 278): Solution and Explanation
Versions are numbered 1 to n, and once a version is bad, every later version is bad too. Using an API isBadVersion(v), find the first bad version while calling the API as few times as possible.
Watch it run step by step
Try your own input and write the code →Intuition
The obvious answer is to check versions 1, 2, 3 and so on until one comes back bad. That makes up to n API calls, and n can be over two billion, so a linear scan is far too slow.
The key fact is that the versions form a sorted boolean sequence: a run of good versions followed by a run of bad ones, like F F F T T. Any time a sequence is split by a monotonic condition, binary search can find the boundary. Pick the middle version. If it is bad, the first bad version is either this one or something earlier, so you can discard everything to its right but must keep the middle itself. If it is good, the first bad version is strictly later, so you discard the middle and everything to its left.
This is the lower-bound form of binary search, where the loop runs while left < right and the bad branch sets right = mid rather than mid - 1. The range shrinks every iteration, and when left and right meet they point at the boundary. There is one practical trap: computing the midpoint as (left + right) / 2 can overflow a 32-bit int when n is near the maximum, so the reference code uses left + (right - left) // 2.
Approach: Lower-bound binary search
- Set
left = 1andright = n, the full range of versions that could be the first bad one. - While
left < right, computemid = left + (right - left) // 2to avoid overflow in fixed-width languages. - If
isBadVersion(mid)is true, the answer is atmidor earlier, so setright = mid. - Otherwise the answer is after
mid, so setleft = mid + 1. - When the loop exits,
left == right, and that version is the first bad one, so returnleft.
Step-by-step example
n = 5, first bad version = 4
- Start with
left = 1,right = 5. The midpoint is 1 + (5 - 1) // 2 = 3. isBadVersion(3)is false, so the first bad version is after 3. Setleft = 4.- Now
left = 4,right = 5, and the midpoint is 4 + (5 - 4) // 2 = 4. isBadVersion(4)is true, so setright = 4.- Now
left == right == 4, the loop stops, and the function returns 4 after only two API calls.
Code: Python, Java, C++
1class Solution:
2 def firstBadVersion(self, n: int) -> int:
3 left, right = 1, n
4 while left < right:
5 mid = left + (right - left) // 2
6 if isBadVersion(mid):
7 right = mid
8 else:
9 left = mid + 1
10 return left1public class Solution extends VersionControl {
2 public int firstBadVersion(int n) {
3 int left = 1, right = n;
4 while (left < right) {
5 int mid = left + (right - left) / 2;
6 if (isBadVersion(mid)) {
7 right = mid;
8 } else {
9 left = mid + 1;
10 }
11 }
12 return left;
13 }
14}1class Solution {
2public:
3 int firstBadVersion(int n) {
4 int left = 1, right = n;
5 while (left < right) {
6 int mid = left + (right - left) / 2;
7 if (isBadVersion(mid)) {
8 right = mid;
9 } else {
10 left = mid + 1;
11 }
12 }
13 return left;
14 }
15};Time and space complexity
O(log n)
Each iteration halves the candidate range and makes exactly one API call, so there are about log₂ n calls. For n near two billion that is roughly 31 calls.
O(1)
Only the two bounds and the midpoint are stored.
Other approaches
Binary search with an answer variable (time O(log n), space O(1))
Use the classic left <= right loop, record mid as the best answer whenever it is bad, then set right = mid - 1. It returns the same result and some people find it easier to reason about, at the cost of one extra variable.
Linear scan (time O(n), space O(1))
Call the API on each version from 1 upward and return the first bad one. It is simple but makes up to n calls, which is far too slow for large n.
Common mistakes
- Computing
(left + right) / 2in Java or C++. Withnclose to 2^31 - 1, the sum overflows and the midpoint becomes negative. - Setting
right = mid - 1whenmidis bad while usingleft < right. That can skip over the answer whenmiditself is the first bad version. - Mixing
left <= rightwithright = mid. Ifleft == rightand the version is bad, the range never shrinks and the loop runs forever. - Starting
leftat 0. Versions are numbered from 1, and calling the API with 0 is outside the valid range.
Frequently asked questions
Why use left + (right - left) / 2 instead of (left + right) / 2?
Both give the same midpoint mathematically, but left + right can exceed the largest 32-bit integer when n is huge. Subtracting first keeps every intermediate value within range.
How many API calls does First Bad Version make?
About log₂ n, rounded up. For the largest inputs that is around 31 calls, compared with potentially billions for a linear scan.
Is First Bad Version the same as finding a lower bound?
Yes. It is the lower-bound search over a sorted sequence of booleans, finding the first index where the condition becomes true. The same template solves Search Insert Position and many answer-space searches.
Why does the loop use left < right instead of left <= right?
With left < right, the loop stops when the range has shrunk to a single version, and that version must be the answer because a bad version is guaranteed to exist. Using <= with right = mid would never shrink a one-element range whose version is bad, so the loop would spin forever.