|
| 1 | +/** |
| 2 | + * @param {funciton} isBadVersion Function returning true if passed version is bad. |
| 3 | + * @return {function} Function that returns first bad version. |
| 4 | + * @summary First Bad Version {@link https://leetcode.com/problems/first-bad-version/} |
| 5 | + * @description For a list of versions, return first bad verions of software. |
| 6 | + * Space O(1) - Always using 3 variables. |
| 7 | + * Time O(logn) - Binary search - we always divide remaining possibilites in 2. |
| 8 | + */ |
| 9 | +const solution = isBadVersion => { |
| 10 | + /** |
| 11 | + * @param {integer} n Total versions |
| 12 | + * @return {integer} The first bad version |
| 13 | + */ |
| 14 | + return n => { |
| 15 | + let left = 1; |
| 16 | + let right = n; |
| 17 | + |
| 18 | + while (left < right) { |
| 19 | + let guess = parseInt(left + (right - left) / 2); |
| 20 | + |
| 21 | + if (isBadVersion(guess)) right = guess; |
| 22 | + else left = guess + 1; |
| 23 | + } |
| 24 | + |
| 25 | + return left; |
| 26 | + }; |
| 27 | +}; |
0 commit comments