# 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 `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.**

### Solution:

You could start from  the beginning and do a linear search thorugh your product versions one by one until you land on the bad one however if consider that you have a 2500  product versions, if it takes one minute to search and test one version, it would therefore take you almost 2 days to arrive to answer in the worst-case scenario that the first bad version is at `n-2 position. Time Complexity : O(N)` &#x20;

We can do better with the Binary Search Algorithm

```java
/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int start = 1, end = n;
        
        while(start <= end){
            int mid = end + (start - end) / 2;
            if(isBadVersion(mid)){
                end = mid - 1;
            }
            else{
                start = mid + 1;
            }
        }
        return start;
    }
}
```

`Time Complexity: O(logN)`
