Binary search for the first bad version via isBad
Suppose you have n versions of a product, and you want to find the first version that introduced a bug, causing all the following versions to also be bad. Given a function isBad that takes a version number and returns true if the version is bad and false otherwise, implement a function firstBadVersion that utilizes a binary search algorithm to efficiently find and return the first bad version. Finding the first bad version efficiently is a classic binary search problem.
Your function should minimize the number of calls to the isBad function. Implement firstBadVersion such that it returns a closure which accepts a single integer parameter version, representing the total number of versions, and returns the first bad version number, or -1 if no bad version is found.
Function Signature:
function firstBadVersion(isBad: (version: number) => boolean): (version: number) => number
Example Usage:
const isBad = (version) => version >= 4;
const findFirstBad = firstBadVersion(isBad);
console.log(findFirstBad(5)); // Output: 4
This problem tests your ability to apply binary search in a practical scenario, optimizing for efficiency in terms of time complexity and minimizing the use of resources such as network or database calls.