To efficiently solve this problem, we can utilize a binary search algorithm. The goal is to find the first bad version by performing a binary search on the range of versions.
Here’s the algorithm:
- Initialize the left pointer to 1 and the right pointer to n.
- While the left pointer is less than or equal to the right pointer: a. Calculate the middle version as the average of the left and right pointers: mid = (left + right) / 2. b. Use the isBadVersion(mid) API to check if the middle version is bad.
- If isBadVersion(mid) returns true, it means the current version is bad. In this case, update the right pointer to mid – 1 and continue the search in the left half.
- If isBadVersion(mid) returns false, it means the current version is not bad. In this case, update the left pointer to mid + 1 and continue the search in the right half.
- Return the left pointer as the first bad version.
By employing the binary search approach, we can significantly reduce the number of API calls, making the solution more efficient.
Here’s the implementation in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def firstBadVersion(n): left = 1 right = n while left <= right: mid = (left + right) // 2 if isBadVersion(mid): right = mid - 1 else: left = mid + 1 return left |
Here’s the solution implemented in C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
int firstBadVersion(int n) { int left = 1; int right = n; while (left <= right) { int mid = left + (right - left) / 2; if (isBadVersion(mid)) { right = mid - 1; } else { left = mid + 1; } } return left; } |
Recent Comments