First Bad Version (LeetCode 278): Solution and Explanation

Easy
Binary Search
Interactive

Versions are numbered 1 to n, and once a version is bad, every later version is bad too. Using an API isBadVersion(v), find the first bad version while calling the API as few times as possible.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The obvious answer is to check versions 1, 2, 3 and so on until one comes back bad. That makes up to n API calls, and n can be over two billion, so a linear scan is far too slow.

The key fact is that the versions form a sorted boolean sequence: a run of good versions followed by a run of bad ones, like F F F T T. Any time a sequence is split by a monotonic condition, binary search can find the boundary. Pick the middle version. If it is bad, the first bad version is either this one or something earlier, so you can discard everything to its right but must keep the middle itself. If it is good, the first bad version is strictly later, so you discard the middle and everything to its left.

This is the lower-bound form of binary search, where the loop runs while left < right and the bad branch sets right = mid rather than mid - 1. The range shrinks every iteration, and when left and right meet they point at the boundary. There is one practical trap: computing the midpoint as (left + right) / 2 can overflow a 32-bit int when n is near the maximum, so the reference code uses left + (right - left) // 2.

Approach: Lower-bound binary search

  1. Set left = 1 and right = n, the full range of versions that could be the first bad one.
  2. While left < right, compute mid = left + (right - left) // 2 to avoid overflow in fixed-width languages.
  3. If isBadVersion(mid) is true, the answer is at mid or earlier, so set right = mid.
  4. Otherwise the answer is after mid, so set left = mid + 1.
  5. When the loop exits, left == right, and that version is the first bad one, so return left.

Step-by-step example

n = 5, first bad version = 4
  1. Start with left = 1, right = 5. The midpoint is 1 + (5 - 1) // 2 = 3.
  2. isBadVersion(3) is false, so the first bad version is after 3. Set left = 4.
  3. Now left = 4, right = 5, and the midpoint is 4 + (5 - 4) // 2 = 4.
  4. isBadVersion(4) is true, so set right = 4.
  5. Now left == right == 4, the loop stops, and the function returns 4 after only two API calls.

Code: Python, Java, C++

1class Solution:
2    def firstBadVersion(self, n: int) -> int:
3        left, right = 1, n
4        while left < right:
5            mid = left + (right - left) // 2
6            if isBadVersion(mid):
7                right = mid
8            else:
9                left = mid + 1
10        return left

Time and space complexity

Time

O(log n)

Each iteration halves the candidate range and makes exactly one API call, so there are about log₂ n calls. For n near two billion that is roughly 31 calls.

Space

O(1)

Only the two bounds and the midpoint are stored.

Other approaches

Binary search with an answer variable (time O(log n), space O(1))

Use the classic left <= right loop, record mid as the best answer whenever it is bad, then set right = mid - 1. It returns the same result and some people find it easier to reason about, at the cost of one extra variable.

Linear scan (time O(n), space O(1))

Call the API on each version from 1 upward and return the first bad one. It is simple but makes up to n calls, which is far too slow for large n.

Common mistakes

  • Computing (left + right) / 2 in Java or C++. With n close to 2^31 - 1, the sum overflows and the midpoint becomes negative.
  • Setting right = mid - 1 when mid is bad while using left < right. That can skip over the answer when mid itself is the first bad version.
  • Mixing left <= right with right = mid. If left == right and the version is bad, the range never shrinks and the loop runs forever.
  • Starting left at 0. Versions are numbered from 1, and calling the API with 0 is outside the valid range.

Frequently asked questions

Why use left + (right - left) / 2 instead of (left + right) / 2?

Both give the same midpoint mathematically, but left + right can exceed the largest 32-bit integer when n is huge. Subtracting first keeps every intermediate value within range.

How many API calls does First Bad Version make?

About log₂ n, rounded up. For the largest inputs that is around 31 calls, compared with potentially billions for a linear scan.

Is First Bad Version the same as finding a lower bound?

Yes. It is the lower-bound search over a sorted sequence of booleans, finding the first index where the condition becomes true. The same template solves Search Insert Position and many answer-space searches.

Why does the loop use left < right instead of left <= right?

With left < right, the loop stops when the range has shrunk to a single version, and that version must be the answer because a bad version is guaranteed to exist. Using <= with right = mid would never shrink a one-element range whose version is bad, so the loop would spin forever.