Binary Search is the optimal approach for this problem. By dividing
the search
space
in half at each step, we can efficiently
find the
first bad version. The key is to
adjust the search range
based on whether the current
midpoint
is a bad version
or not. We continue this process until we've narrowed down to the exact version where the transition
from good to bad occurs.
/* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class Solution extends VersionControl { public int firstBadVersion(int n) { int start = 1; int end = n; while(start<=end){ int mid = end - (end-start)/2; if(isBadVersion(mid)) end = mid-1; else start = mid+1; } return start; } }
The algorithm uses binary search, which halves the search space at each step, resulting in a logarithmic time complexity.
The algorithm uses a constant amount of extra space, regardless of the input size.