Easy
041First Bad Version
Given n and the first bad version value, return the first bad version using the least number of checks.
EXAMPLES
Example 1
Input
{
"n": 5,
"bad": 4
}
Output
4FUNCTION SHAPE
n: intbad: int→intSOLUTION NOTE
Classic min template. Function is monotone: FFFTTT... Find first T.
Reveal reference solution +
pythonREFERENCE
def firstBadVersion(self, n: int) -> int:
left, right = 1, n
while left < right:
mid = left + (right - left) // 2
if isBadVersion(mid):
right = mid
else:
left = mid + 1
return leftTime
O(log n)Space
O(1)