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.

&nbsp;
Example 1:

Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -&gt; false
call isBadVersion(5)&nbsp;-&gt; true
call isBadVersion(4)&nbsp;-&gt; true
Then 4 is the first bad version.


Example 2:

Input: n = 1, bad = 1
Output: 1


&nbsp;
Constraints:


	1 &lt;= bad &lt;= n &lt;= 231 - 1


class Solution:
    def firstBadVersion(self, n: int) -> int:
        fast, slow = int(n/2), n
        diff = abs(fast-slow)
        while isBadVersion(fast) == isBadVersion(slow) or diff > 1:
            fast, slow = fast + (-1)**isBadVersion(fast) * (int(diff/2) or 1), fast
            diff = abs(fast-slow)
        return fast if isBadVersion(fast) else slow
/* 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 s = 0; int e = n;
        
        while(s < e) {
            int mid = s +(e-s)/2;
            
            if(isBadVersion(mid)){
                e = mid ;
            } else {
                s = mid +1;
            }
        }
        return e ;
    }
}
class Solution {
public:
    int firstBadVersion(int n) {
	//Using Binary Search
        int lo = 1, hi = n, mid;
        while (lo < hi) {
            mid = lo + (hi - lo) / 2;
            if (isBadVersion(mid)) hi = mid;
            else lo = mid+1;
        }
        return lo;
    }
};
/**
 * Definition for isBadVersion()
 *
 * @param {integer} version number
 * @return {boolean} whether the version is bad
 * isBadVersion = function(version) {
 * ...
 * };
 */

/**
 * @param {function} isBadVersion()
 * @return {function}
 */
var solution = function(isBadVersion) {
    /**
     * @param {integer} n Total versions
     * @return {integer} The first bad version
     */
    return function(n) {
        let ceiling = n
        let floor = 1
        let firstBadVersion = -1

        while (floor <= ceiling) {
            const middle = Math.floor((ceiling + floor) / 2)

            if (isBadVersion(middle)) {

                firstBadVersion = middle
                ceiling = middle - 1
            } else {
                floor = middle + 1
            }
        }

        return firstBadVersion
    };
};
First Bad Version