
Sponsored
Sponsored
This approach uses the concept of binary search to efficiently find the first bad version by minimizing the number of calls made to the given isBadVersion API. By leveraging binary search, we can reduce the problem set size by half with each iteration, therefore achieving O(log n) time complexity.
Time Complexity: O(log n)
Space Complexity: O(1)
1public class Solution extends VersionControl {
2 public int firstBadVersion(int n) {
3 int left = 1, right = n;
4 while (left < right) {
5 int mid = left + (right - left) / 2;
6 if (isBadVersion(mid)) right = mid;
7 else left = mid + 1;
8 }
9 return left;
10 }
11}The Java solution follows the same binary search logic. We repeatedly narrow the search range by adjusting left and right based on the mid-point value's status as bad or not. The convergence of left and right yields the first bad version.
This approach explores a recursive implementation of the binary search technique to identify the first bad version. Employing recursion allows the continual division of the search problem into smaller subproblems until the solution is found.
Time Complexity: O(log n)
Space Complexity: O(log n) - due to recursion stack
1#include <stdbool.h>
// Forward declaration of isBadVersion API.
bool isBadVersion(int version);
int binarySearch(int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
if (isBadVersion(mid)) return binarySearch(left, mid);
else return binarySearch(mid + 1, right);
}
return left;
}
class Solution {
public:
int firstBadVersion(int n) {
return binarySearch(1, n);
}
};The solution takes advantage of C++'s support for recursive functions to spot the first bad version through binarySearch. With each recursive call, it assesses the midpoint and adjusts the search range, seeking to locate the first bad version.