Leetcode 278. First Bad Version
You are a product manager, and currently 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 boolean isBadVersion(int 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.
n
(the number of versions)?
isBadVersion(int version)
take a constant time to execute?
To minimize the number of calls to isBadVersion
, a binary search strategy is appropriate. Binary search will reduce the number of calls to the function from O(n) to O(log n).
left
and right
to 1 and n
respectively.mid = left + (right - left) / 2
.isBadVersion(mid)
to check if mid
is a bad version.
mid
is a bad version, then the first bad version must be at mid
or before it, so adjust the right pointer to mid
.mid
is not a bad version, then the first bad version must be after mid
, so adjust the left pointer to mid + 1
.public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int left = 1;
int right = n;
while (left < right) {
int mid = left + (right - left) / 2;
if (isBadVersion(mid)) {
right = mid; // Look on the left side including mid
} else {
left = mid + 1; // Look on the right side excluding mid
}
}
return left;
}
}
This solution efficiently finds the first bad version by reducing the problem size in half with each iteration.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?