15% off all plans & roadmaps Use code

See plans

First Bad Version

Updated

TL;DR: You need the first version that fails, and every version after it fails too. Binary search on this yes-then-no pattern finds it in about log2 n API calls.

Problem

You are a product manager leading a team that develops a new product. The latest version fails the quality check. Each version is built on the one before it, so every version after a bad version is also bad.

Suppose there are n versions [1, 2, ..., n]. Your job is to find the first bad version, which causes every version after it to be bad.

The API bool isBadVersion(version) returns whether version is bad. Write a function that finds the first bad version while calling the API as few times as possible.

Example 1

Input: n = 5, bad = 4
Output: 4
Explanation: The API returns false for version 3, true for version 5, and true for version 4. Version 4 is the first bad version.

Example 2

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

Constraints

  • 1 <= bad <= n <= 2^31 - 1

Constraints that matter

  • n can be 2^31 - 1, so a scan that checks every version can make about 2 billion API calls. That rules out linear search in the worst case.
  • Once a version is bad, every later version is bad. That monotone pattern is what lets you discard half the range after each call.
  • Compute the midpoint as left + (right - left) / 2. In Java and C++, left + right can exceed the 32-bit int limit when n is near 2^31 - 1.
  • The input guarantees that a bad version exists between 1 and n. The loop can therefore end on a single candidate without any extra check.

View on LeetCode

Hints

Hint 1

The versions form a yes-then-no pattern.

Hint 2

Start at version 1 and call the API on each version in turn.

Solution

Intuition

The versions form a yes-then-no pattern. Every version before the first bad one is good, and every version from there on is bad. A sorted boolean sequence like this is the signature of binary search on a monotone condition. You are looking for the exact point where the value flips.

Picture a row of light switches where every switch from some point onward is on. Each test checks one switch in the middle, and the range of left and right is the stretch that might still hold the first on switch.

Pick the middle version and ask the API about it. A bad answer means the first bad version is either the middle or somewhere to its left, so the right half can go. A good answer means the first bad version must come after the middle, so the left half and the middle can go. Each call removes about half of the remaining candidates.

The loop keeps one invariant: the first bad version lies inside the closed range from left to right. It stops when the range holds a single version. That version must be the answer, because the invariant still holds and nothing else is left in range.

Watch the pattern animation

Worked example

Input: n = 1000000, bad = 543210
Output: 543210
Explanation: Versions 1 through 543209 are good, and version 543210 is the first bad one. The brute force scan calls the API 543210 times, while binary search needs only 20 calls.

Approach 1: Brute force

Start at version 1 and call the API on each version in turn. Stop at the first version that returns true, because no earlier version can be the first bad one.

The scan is correct because the bad versions form a suffix. The first true you meet is the first bad version. The scan never needs to look past it.

The cost is one API call per version. If the first bad version is near n, the scan spends almost all of its calls on good versions that only tell you the answer is later.

Steps

  1. Set version to 1.
  2. Call isBadVersion(version). If it returns true, return version.
  3. Otherwise add 1 to version and repeat.
  4. If the loop reaches n without a true result, return n, since n must be bad.

Dry run

Trace on n = 1000000 and bad = 543210. The function never sees bad, so it only learns answers from the API.

The loop calls isBadVersion(1) and gets false. It calls isBadVersion(2) and gets false, and it keeps going the same way. Every call through version 543209 returns false.

The call isBadVersion(543210) returns true, so the loop returns 543210. The trace made 543210 API calls in total.

Complexity

TimeO(n) API calls in the worst case
SpaceO(1)

Let n be the number of versions. The loop body runs at most n - 1 times, and each run makes one API call and a constant amount of other work. The worst case is a first bad version at n, which forces every check. The loop stores only the counter, so the extra space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def firstBadVersion(self, n: int) -> int:
        # Binary search: the bad versions form a suffix, so narrow the range each call.
        lo, hi = 1, n
        while lo < hi:
            mid = lo + (hi - lo) // 2
            if isBadVersion(mid):
                # mid is bad, so the first bad version is mid or earlier.
                hi = mid
            else:
                # mid is good, so the first bad version is after mid.
                lo = mid + 1
        return lo

The On Sorted Array/List infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

On Sorted Array/List

Part of Binary Search Patterns

Approach 2: Binary search on the boundaryOptimalOn Sorted Array/List

What's slow: the scan spends one call per version, so it wastes calls on the long good prefix. Each call tells you only that the answer is further right, one version at a time.

The insight that fixes it: one call at the midpoint rules out half the range. A bad midpoint means the answer is at or left of mid. A good midpoint means the answer is strictly right of mid.

Keep the range as the search state. Each call shrinks it, and the loop ends when one candidate remains.

Steps

  1. Set left to 1 and right to n.
  2. While left < right, compute mid = left + (right - left) / 2.
  3. If isBadVersion(mid) is true, set right = mid, because mid may be the first bad version.
  4. Otherwise set left = mid + 1, because mid is good and the answer lies after it.
  5. When the loop ends, return left.

Dry run

Trace on n = 1000000 and bad = 543210. Each row shows the range before the call, the midpoint, and the API answer. The API answers come from the hidden value bad = 543210.

StepleftrightmidisBadVersion(mid)Action
111000000500000falseleft = 500001
25000011000000750000trueright = 750000
3500001750000625000trueright = 625000
4500001625000562500trueright = 562500
5500001562500531250falseleft = 531251
6531251562500546875trueright = 546875
7531251546875539063falseleft = 539064
8539064546875542969falseleft = 542970
9542970546875544922trueright = 544922
10542970544922543946trueright = 543946
11542970543946543458trueright = 543458
12542970543458543214trueright = 543214
13542970543214543092falseleft = 543093
14543093543214543153falseleft = 543154
15543154543214543184falseleft = 543185
16543185543214543199falseleft = 543200
17543200543214543207falseleft = 543208
18543208543214543211trueright = 543211
19543208543211543209falseleft = 543210
20543210543211543210trueright = 543210

The loop stops because left and right are both 543210. The function returns 543210 after 20 API calls.

Complexity

TimeO(log n)
SpaceO(1)

Let n be the number of versions. Each iteration keeps either the left part or the right part of the range, so the range size at least halves, rounding up. The range starts at n and the loop stops at size 1, so there are at most about log2(n) iterations. For n up to 2^31 - 1 that is at most 31 iterations, each making one API call and constant arithmetic. The code keeps three integers, so space is O(1).

PythonTested in our runner

class Solution:
    def firstBadVersion(self, n: int) -> int:
        left, right = 1, n
        while left < right:
            # Written this way so the midpoint never overflows in other languages.
            mid = left + (right - left) // 2
            if isBadVersion(mid):
                # mid could be the first bad version, so keep it in range.
                right = mid
            else:
                # mid is good, so the answer lies strictly after it.
                left = mid + 1
        return left

Common mistakes

  • mid = (left + right) / 2 in Java, C++ or C#. The sum can exceed 2^31 - 1 when n is large. Use mid = left + (right - left) / 2.
  • right = mid - 1 after a bad answer. Mid may be the first bad version, so discarding it can skip the answer. Set right = mid.
  • while (left <= right) combined with right = mid. When left equals right, mid never changes and the loop never ends. Use while (left < right).
  • left = mid after a good answer. Mid is known to be good, so the range never shrinks and the loop stalls. Set left = mid + 1.
  • Starting with left = 0. Version 0 does not exist, and the search can return a value outside the valid range. Start left at 1.

Edge cases

  • n = 1, bad = 1: the loop never runs, so the function returns 1 with zero API calls.
  • n = 2, bad = 1: mid is 1, which is bad, so right becomes 1 and the function returns 1.
  • n = 2, bad = 2: mid is 1, which is good, so left becomes 2 and the function returns 2.
  • n = 2^31 - 1, bad = n: the midpoint stays inside the int range, and the search returns n after about 31 calls.
  • n = 2^31 - 1, bad = 1: every midpoint is bad, so right keeps shrinking until left and right are both 1.

Follow-ups interviewers ask

Can you find the first bad version with fewer than about log2(n) calls?
No, not in the worst case. Each call returns one bit, and there are n possible answers. You need at least ceil(log2 n) calls to tell them apart, and binary search meets that bound.
What if you write the search recursively?
You can. The recursion depth is about log2(n), which is at most 31 frames, so the stack is safe. The iterative version uses O(1) extra space and avoids call overhead, which is why the page's code is iterative.
What if the bad versions are not contiguous, and a bad version can later be fixed?
Binary search no longer works. It needs the predicate to be monotone, so once a version is bad every later version stays bad. Without that, a midpoint answer says nothing about the half you discard, and you would need to check every version.

First Bad Version FAQ

What is the time complexity of First Bad Version?

The optimal solution makes O(log n) API calls and uses O(1) extra space. The brute force scan makes O(n) calls, which is too many when n can reach 2^31 - 1.

Why use binary search for First Bad Version?

The versions follow a yes-then-no pattern: all good, then all bad. Binary search finds the exact flip point in a sorted boolean sequence like this, and it halves the range on every call.

Can First Bad Version be solved in O(1) extra space?

Yes. The iterative loop keeps only left, right and mid. A recursive version would use O(log n) stack space, so the iterative form is the one to write.

Why does the code compute mid as left + (right - left) / 2?

It gives the same result as (left + right) / 2 without overflow. In Java and C++ the sum can exceed 2^31 - 1 when n is close to the maximum.

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

When left equals right, one candidate is left, and it must be the answer. With left <= right and right set to mid, the loop can repeat on the same mid forever.

Asked at

See which companies ask this — Pro

Practise it