278. First Bad Version

Linear Solution

/**
 * 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) {
        while(n >= 0) {
            if (!isBadVersion(n)) {
                return n+1;
            }
            n--;
        }
        return 1;
    };
};

Better Solution

/**
 * 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 left = 0;
        let right = n;
        
        while(left < right) {
            const mid = (left + (right - left) / 2 ) | 0;
            
            if (isBadVersion(mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left; // Or right
    };
};

Complexity

  • Time Complexity: O(logN), or how many times can we halve the array until a single element remains.
  • Space Complexity: O(1), we are not using any extra memory, just moving pointers.

All Solutions