15% off all plans & roadmaps Use code
See plansFirst Bad Version
- LeetCode 278
- Easy
- Binary Search Patterns
- On Sorted Array/List
Updated
TL;DR: You need the first version that fails, and every version after it fails too. Binary search on this yes-then-no pattern finds it in about log2 n API calls.
Problem
You are a product manager leading a team that develops a new product. The latest version fails the quality check. Each version is built on the one before it, so every version after a bad version is also bad.
Suppose there are n versions [1, 2, ..., n]. Your job is to find the first bad version, which causes every version after it to be bad.
The API bool isBadVersion(version) returns whether version is bad. Write a function that finds the first bad version while calling the API as few times as possible.
Example 1
Input: n = 5, bad = 4 Output: 4 Explanation: The API returns false for version 3, true for version 5, and true for version 4. Version 4 is the first bad version.
Example 2
Input: n = 1, bad = 1 Output: 1
Constraints
1 <= bad <= n <= 2^31 - 1
Constraints that matter
- n can be 2^31 - 1, so a scan that checks every version can make about 2 billion API calls. That rules out linear search in the worst case.
- Once a version is bad, every later version is bad. That monotone pattern is what lets you discard half the range after each call.
- Compute the midpoint as left + (right - left) / 2. In Java and C++, left + right can exceed the 32-bit int limit when n is near 2^31 - 1.
- The input guarantees that a bad version exists between 1 and n. The loop can therefore end on a single candidate without any extra check.
Hints
Hint 1
The versions form a yes-then-no pattern.
Hint 2
Start at version 1 and call the API on each version in turn.
Solution
Intuition
The versions form a yes-then-no pattern. Every version before the first bad one is good, and every version from there on is bad. A sorted boolean sequence like this is the signature of binary search on a monotone condition. You are looking for the exact point where the value flips.
Picture a row of light switches where every switch from some point onward is on. Each test checks one switch in the middle, and the range of left and right is the stretch that might still hold the first on switch.
Pick the middle version and ask the API about it. A bad answer means the first bad version is either the middle or somewhere to its left, so the right half can go. A good answer means the first bad version must come after the middle, so the left half and the middle can go. Each call removes about half of the remaining candidates.
The loop keeps one invariant: the first bad version lies inside the closed range from left to right. It stops when the range holds a single version. That version must be the answer, because the invariant still holds and nothing else is left in range.
Worked example
Input: n = 1000000, bad = 543210 Output: 543210 Explanation: Versions 1 through 543209 are good, and version 543210 is the first bad one. The brute force scan calls the API 543210 times, while binary search needs only 20 calls.
Approach 1: Brute force
Start at version 1 and call the API on each version in turn. Stop at the first version that returns true, because no earlier version can be the first bad one.
The scan is correct because the bad versions form a suffix. The first true you meet is the first bad version. The scan never needs to look past it.
The cost is one API call per version. If the first bad version is near n, the scan spends almost all of its calls on good versions that only tell you the answer is later.
Steps
- Set version to 1.
- Call isBadVersion(version). If it returns true, return version.
- Otherwise add 1 to version and repeat.
- If the loop reaches n without a true result, return n, since n must be bad.
Dry run
Trace on n = 1000000 and bad = 543210. The function never sees bad, so it only learns answers from the API.
The loop calls isBadVersion(1) and gets false. It calls isBadVersion(2) and gets false, and it keeps going the same way. Every call through version 543209 returns false.
The call isBadVersion(543210) returns true, so the loop returns 543210. The trace made 543210 API calls in total.
Complexity
| Time | O(n) API calls in the worst case |
|---|---|
| Space | O(1) |
Let n be the number of versions. The loop body runs at most n - 1 times, and each run makes one API call and a constant amount of other work. The worst case is a first bad version at n, which forces every check. The loop stores only the counter, so the extra space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def firstBadVersion(self, n: int) -> int:
# Binary search: the bad versions form a suffix, so narrow the range each call.
lo, hi = 1, n
while lo < hi:
mid = lo + (hi - lo) // 2
if isBadVersion(mid):
# mid is bad, so the first bad version is mid or earlier.
hi = mid
else:
# mid is good, so the first bad version is after mid.
lo = mid + 1
return loC++Tested in our runner
class Solution {
public:
int firstBadVersion(int n) {
// Binary search over the monotone bad-version suffix.
int lo = 1, hi = n;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (isBadVersion(mid)) {
hi = mid;
} else {
lo = mid + 1;
}
}
return lo;
}
};JavaScriptTested in our runner
var firstBadVersion = function(n) {
// Binary search for the first bad version in [1, n].
let lo = 1;
let hi = n;
while (lo < hi) {
// Midpoint without overflow.
const mid = lo + Math.floor((hi - lo) / 2);
if (isBadVersion(mid)) {
// mid is bad, so the first bad version is mid or earlier.
hi = mid;
} else {
// mid is good, so the first bad version is after mid.
lo = mid + 1;
}
}
return lo;
};GoTested in our runner
func firstBadVersion(n int) int {
// Binary search for the first bad version in O(log n) API calls.
lo, hi := 1, n
for lo < hi {
// Avoid overflow when computing the midpoint.
mid := lo + (hi-lo)/2
if isBadVersion(mid) {
// mid is bad, so the first bad version is at mid or earlier.
hi = mid
} else {
// mid is good, so the first bad version is after mid.
lo = mid + 1
}
}
return lo
}C#Tested in our runner
public class Solution : VersionControl { public int firstBadVersion(int n) { int lo = 1, hi = n; /* Binary search: the bad versions form a suffix, so halve the range each call to stay within about log2(n) API calls. */ while (lo < hi) { int mid = lo + (hi - lo) / 2; if (isBadVersion(mid)) hi = mid; else lo = mid + 1; } return lo; } }The On Sorted Array/List infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
On Sorted Array/List
Part of Binary Search Patterns
Approach 2: Binary search on the boundaryOptimalOn Sorted Array/List
What's slow: the scan spends one call per version, so it wastes calls on the long good prefix. Each call tells you only that the answer is further right, one version at a time.
The insight that fixes it: one call at the midpoint rules out half the range. A bad midpoint means the answer is at or left of mid. A good midpoint means the answer is strictly right of mid.
Keep the range as the search state. Each call shrinks it, and the loop ends when one candidate remains.
Steps
- Set left to 1 and right to n.
- While left < right, compute mid = left + (right - left) / 2.
- If isBadVersion(mid) is true, set right = mid, because mid may be the first bad version.
- Otherwise set left = mid + 1, because mid is good and the answer lies after it.
- When the loop ends, return left.
Dry run
Trace on n = 1000000 and bad = 543210. Each row shows the range before the call, the midpoint, and the API answer. The API answers come from the hidden value bad = 543210.
| Step | left | right | mid | isBadVersion(mid) | Action |
|---|---|---|---|---|---|
| 1 | 1 | 1000000 | 500000 | false | left = 500001 |
| 2 | 500001 | 1000000 | 750000 | true | right = 750000 |
| 3 | 500001 | 750000 | 625000 | true | right = 625000 |
| 4 | 500001 | 625000 | 562500 | true | right = 562500 |
| 5 | 500001 | 562500 | 531250 | false | left = 531251 |
| 6 | 531251 | 562500 | 546875 | true | right = 546875 |
| 7 | 531251 | 546875 | 539063 | false | left = 539064 |
| 8 | 539064 | 546875 | 542969 | false | left = 542970 |
| 9 | 542970 | 546875 | 544922 | true | right = 544922 |
| 10 | 542970 | 544922 | 543946 | true | right = 543946 |
| 11 | 542970 | 543946 | 543458 | true | right = 543458 |
| 12 | 542970 | 543458 | 543214 | true | right = 543214 |
| 13 | 542970 | 543214 | 543092 | false | left = 543093 |
| 14 | 543093 | 543214 | 543153 | false | left = 543154 |
| 15 | 543154 | 543214 | 543184 | false | left = 543185 |
| 16 | 543185 | 543214 | 543199 | false | left = 543200 |
| 17 | 543200 | 543214 | 543207 | false | left = 543208 |
| 18 | 543208 | 543214 | 543211 | true | right = 543211 |
| 19 | 543208 | 543211 | 543209 | false | left = 543210 |
| 20 | 543210 | 543211 | 543210 | true | right = 543210 |
The loop stops because left and right are both 543210. The function returns 543210 after 20 API calls.
Complexity
| Time | O(log n) |
|---|---|
| Space | O(1) |
Let n be the number of versions. Each iteration keeps either the left part or the right part of the range, so the range size at least halves, rounding up. The range starts at n and the loop stops at size 1, so there are at most about log2(n) iterations. For n up to 2^31 - 1 that is at most 31 iterations, each making one API call and constant arithmetic. The code keeps three integers, so space is O(1).
PythonTested in our runner
class Solution:
def firstBadVersion(self, n: int) -> int:
left, right = 1, n
while left < right:
# Written this way so the midpoint never overflows in other languages.
mid = left + (right - left) // 2
if isBadVersion(mid):
# mid could be the first bad version, so keep it in range.
right = mid
else:
# mid is good, so the answer lies strictly after it.
left = mid + 1
return leftJavaTested in our runner
class Solution extends VersionControl {
public int firstBadVersion(int n) {
int left = 1;
int right = n;
while (left < right) {
// left + right could overflow a 32-bit int, so offset from left.
int mid = left + (right - left) / 2;
if (isBadVersion(mid)) {
// mid could be the first bad version, so keep it in range.
right = mid;
} else {
// mid is good, so the answer lies strictly after it.
left = mid + 1;
}
}
return left;
}
}C++Tested in our runner
class Solution {
public:
int firstBadVersion(int n) {
int left = 1;
int right = n;
while (left < right) {
// left + right could overflow a 32-bit int, so offset from left.
int mid = left + (right - left) / 2;
if (isBadVersion(mid)) {
// mid could be the first bad version, so keep it in range.
right = mid;
} else {
// mid is good, so the answer lies strictly after it.
left = mid + 1;
}
}
return left;
}
};JavaScriptTested in our runner
var firstBadVersion = function(n) {
let left = 1;
let right = n;
while (left < right) {
// Math.floor keeps mid an integer. Values stay below 2^31, so doubles are exact.
const mid = left + Math.floor((right - left) / 2);
if (isBadVersion(mid)) {
// mid could be the first bad version, so keep it in range.
right = mid;
} else {
// mid is good, so the answer lies strictly after it.
left = mid + 1;
}
}
return left;
};GoTested in our runner
func firstBadVersion(n int) int {
left, right := 1, n
for left < right {
// Offset from left so the midpoint never overflows.
mid := left + (right-left)/2
if isBadVersion(mid) {
// mid could be the first bad version, so keep it in range.
right = mid
} else {
// mid is good, so the answer lies strictly after it.
left = mid + 1
}
}
return left
}C#Tested in our runner
public class Solution : VersionControl {
public int firstBadVersion(int n) {
int left = 1;
int right = n;
while (left < right) {
// left + right could overflow a 32-bit int, so offset from left.
int mid = left + (right - left) / 2;
if (isBadVersion(mid)) {
// mid could be the first bad version, so keep it in range.
right = mid;
} else {
// mid is good, so the answer lies strictly after it.
left = mid + 1;
}
}
return left;
}
}Common mistakes
mid = (left + right) / 2in Java, C++ or C#. The sum can exceed 2^31 - 1 when n is large. Usemid = left + (right - left) / 2.right = mid - 1after a bad answer. Mid may be the first bad version, so discarding it can skip the answer. Setright = mid.while (left <= right)combined withright = mid. When left equals right, mid never changes and the loop never ends. Usewhile (left < right).left = midafter a good answer. Mid is known to be good, so the range never shrinks and the loop stalls. Setleft = mid + 1.- Starting with
left = 0. Version 0 does not exist, and the search can return a value outside the valid range. Startleftat 1.
Edge cases
- n = 1, bad = 1: the loop never runs, so the function returns 1 with zero API calls.
- n = 2, bad = 1: mid is 1, which is bad, so right becomes 1 and the function returns 1.
- n = 2, bad = 2: mid is 1, which is good, so left becomes 2 and the function returns 2.
- n = 2^31 - 1, bad = n: the midpoint stays inside the int range, and the search returns n after about 31 calls.
- n = 2^31 - 1, bad = 1: every midpoint is bad, so right keeps shrinking until left and right are both 1.
Follow-ups interviewers ask
- Can you find the first bad version with fewer than about log2(n) calls?
- No, not in the worst case. Each call returns one bit, and there are n possible answers. You need at least ceil(log2 n) calls to tell them apart, and binary search meets that bound.
- What if you write the search recursively?
- You can. The recursion depth is about log2(n), which is at most 31 frames, so the stack is safe. The iterative version uses O(1) extra space and avoids call overhead, which is why the page's code is iterative.
- What if the bad versions are not contiguous, and a bad version can later be fixed?
- Binary search no longer works. It needs the predicate to be monotone, so once a version is bad every later version stays bad. Without that, a midpoint answer says nothing about the half you discard, and you would need to check every version.
First Bad Version FAQ
What is the time complexity of First Bad Version?
The optimal solution makes O(log n) API calls and uses O(1) extra space. The brute force scan makes O(n) calls, which is too many when n can reach 2^31 - 1.
Why use binary search for First Bad Version?
The versions follow a yes-then-no pattern: all good, then all bad. Binary search finds the exact flip point in a sorted boolean sequence like this, and it halves the range on every call.
Can First Bad Version be solved in O(1) extra space?
Yes. The iterative loop keeps only left, right and mid. A recursive version would use O(log n) stack space, so the iterative form is the one to write.
Why does the code compute mid as left + (right - left) / 2?
It gives the same result as (left + right) / 2 without overflow. In Java and C++ the sum can exceed 2^31 - 1 when n is close to the maximum.
Why does the loop use left < right instead of left <= right?
When left equals right, one candidate is left, and it must be the answer. With left <= right and right set to mid, the loop can repeat on the same mid forever.
Asked at
See which companies ask this — Pro
Related problems
- Binary Search · same technique: On Sorted Array/List
- Search Insert Position · same technique: On Sorted Array/List
- Sqrt(x) · same technique: On Sorted Array/List
- Guess Number Higher or Lower · same technique: On Sorted Array/List
- Kth Missing Positive Number · same technique: On Sorted Array/List
- Koko Eating Bananas · next harder, same pattern
- Search in Rotated Sorted Array · same pattern: Binary Search Patterns
- Find Minimum in Rotated Sorted Array · same pattern: Binary Search Patterns
- Search a 2D Matrix · same pattern: Binary Search Patterns
- Find K Closest Elements · same pattern: Binary Search Patterns