Back to blog
Oct 27, 2024
3 min read

First Bad Version

Find the first bad version using binary search given an API to check if a version is bad.

Difficulty: Easy | Acceptance: 47.10% | Paid: No Topics: Binary Search, Interactive

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, …, n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Examples

Example 1:

Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1
Output: 1

Constraints

1 <= bad <= n <= 2³¹ - 1

Linear Scan

Intuition Check each version sequentially from 1 to n until we find the first bad version.

Steps

  • Iterate from version 1 to n
  • Return the first version where isBadVersion returns true
python
# The isBadVersion API is already defined for you.
# def isBadVersion(version: int) -&gt; bool:

class Solution:
    def firstBadVersion(self, n: int) -&gt; int:
        for i in range(1, n + 1):
            if isBadVersion(i):
                return i
        return -1

Complexity

  • Time: O(n)
  • Space: O(1)
  • Notes: Simple but inefficient for large n, makes up to n API calls

Intuition Since all versions after the first bad version are also bad, we have a sorted property that allows binary search to efficiently find the first bad version.

Steps

  • Set left = 1, right = n
  • While left < right:
    • Calculate mid = left + (right - left) / 2 to avoid overflow
    • If isBadVersion(mid) is true, the first bad version is at mid or before, so set right = mid
    • Otherwise, the first bad version is after mid, so set left = mid + 1
  • Return left (or right, they are equal)
python
# The isBadVersion API is already defined for you.
# def isBadVersion(version: int) -&gt; bool:

class Solution:
    def firstBadVersion(self, n: int) -&gt; int:
        left, right = 1, n
        while left &lt; right:
            mid = left + (right - left) // 2
            if isBadVersion(mid):
                right = mid
            else:
                left = mid + 1
        return left

Complexity

  • Time: O(log n)
  • Space: O(1)
  • Notes: Optimal solution, minimizes API calls to at most log₂(n)