First Bad Version
Difficulty: Easy · Pattern: Binary Search · LeetCode #278
Versions 1…n; once a version is bad, all later ones are bad. Given isBadVersion(v) (an API that returns a boolean), find the first bad version with as few calls as possible. (The tests pass n and an isBadVersion function.)
Examples
text
n = 5, first bad = 4 → 4
n = 1, first bad = 1 → 1Hints
- The predicate is false…false, true…true. Find the first true.
- Use
mid = lo + (hi − lo) // 2to avoid overflow in other languages.
Approach
Classic lower-bound binary search on [1, n]: if isBadVersion(mid), the answer is at mid or earlier (hi = mid); else lo = mid + 1. About log₂ n calls.
Complexity
Time: O(log n) API calls. Space: O(1).
Python solution
def firstBadVersion(n, isBadVersion):
lo, hi = 1, n
while lo < hi:
mid = lo + (hi - lo) // 2
if isBadVersion(mid):
hi = mid
else:
lo = mid + 1
return loJavaScript solution
function firstBadVersion(n, isBadVersion) {
let lo = 1, hi = n;
while (lo < hi) { const mid = lo + Math.floor((hi - lo) / 2); if (isBadVersion(mid)) hi = mid; else lo = mid + 1; }
return lo;
}