SDE & MLE Prep

278. First Bad Version

Problem

Versions 1…n were released in order and every version after a bad one is also bad. Using the provided API isBadVersion(version), return the first bad version while calling the API as few times as possible.

Example: n = 5, first bad = 4 → 4

Constraints: n ≤ 2³¹ − 1.

isBadVersion is monotonic (F…F T…T) → find the first true with the lower-bound template, using as few API calls as possible.

Complexity: O(log n) API calls.

class Solution:
    def firstBadVersion(self, n: int) -> int:
        lo, hi = 1, n
        while lo < hi:
            mid = (lo + hi) // 2
            if isBadVersion(mid):      # provided by LeetCode
                hi = mid
            else:
                lo = mid + 1
        return lo