Skip to content
Veltoryx Technologies
FreeProblem 37● EasyLeetCode #278 ↗5 min readUpdated 30 October 2026

First Bad Version

Find the first defective product version using binary search on a boolean API while minimizing calls and preventing integer overflow.

01The problem

You are a product manager 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.

InputOutputWhy
n = 5, bad = 44Versions 1–3 are good; version 4 is the first bad one
n = 1, bad = 11Only one version exists, and it is bad
n = 2, bad = 22Version 1 is good; version 2 is bad

Constraints: 1 ≤ bad ≤ n ≤ 2³¹ − 1.

02How to spot it

  • The sequence of versions evaluated by isBadVersion forms a monotonic boolean array: [false, false, ..., false, true, true, ..., true].
  • We need to find the first true occurrence with the minimum number of API calls.
  • n can reach 2³¹ − 1, making linear inspection completely impossible (up to 2 billion calls).

So: binary search on a boolean condition (lower bound).

03Pseudocode

text
lo = 1 ; hi = n
while lo < hi:
  mid = lo + (hi - lo) / 2
  if isBad(mid): hi = mid
  else: lo = mid + 1
return lo
  1. Versions read: good, good, ..., bad, bad.
  2. If mid is bad, the earliest failure is at mid or to its left: hi = mid.
  3. If mid is good, the earliest failure must be strictly to the right: lo = mid + 1.

04Watch it work

Visualizer · step through the algorithmn = 5, bad = 4
10
21
32
43
54
lohi

Start search for the first defective version in range [1 .. 5].

Pseudocode

  1. lo = 1 ; hi = n
  2. while lo < hi:
  3. mid = lo + (hi - lo) / 2
  4. if isBad(mid): hi = mid
  5. else: lo = mid + 1
  6. return lo

Variables

lo
1
hi
5
n
5
targetBad
4
step 1 / 6

05Step-by-step dry run

  1. 1
    10
    21
    32
    43
    54
    lohi

    Start search for the first defective version in range [1 .. 5].

    lo = 1hi = 5n = 5targetBad = 4

  2. 2
    10
    21
    32
    43
    54
    lomidhi

    Test version 3 with isBadVersion(3): result is GOOD.

    lo = 1hi = 5mid = 3isBad = false

  3. 3
    10
    21
    32
    43
    54
    lohi

    Version 3 is GOOD: the first bad version must be after 3. Set lo = 4.

    lo = 4hi = 5

  4. 4
    10
    21
    32
    43
    54
    lomidhi

    Test version 4 with isBadVersion(4): result is BAD.

    lo = 4hi = 5mid = 4isBad = true

  5. 5
    10
    21
    32
    43
    54
    lohi

    Version 4 is BAD: the first bad version must be 4 or earlier. Set hi = 4.

    lo = 4hi = 4

  6. 6
    10
    21
    32
    43
    54
    firstBad

    Search converged: lo = hi = 4. The first bad version is 4.

    result = 4

06Java solution

FirstBadVersion.java
public class FirstBadVersion {
    static int badVersion = 4;

    static boolean isBadVersion(int version) {
        return version >= badVersion;
    }

    public static int firstBadVersion(int n) {
        int lo = 1, hi = n;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2; // (lo + hi) / 2 can overflow
            if (isBadVersion(mid)) hi = mid; // first bad is mid or earlier
            else lo = mid + 1; // first bad is after mid
        }
        return lo;
    }

    public static void main(String[] args) {
        badVersion = 4;
        System.out.println(firstBadVersion(5));
        badVersion = 1;
        System.out.println(firstBadVersion(1));
        badVersion = 2;
        System.out.println(firstBadVersion(2));
    }
}
Expected output
4
1
2

Tricky lines, decoded

  • lo + (hi - lo) / 2: When n = 2,126,753,390, adding lo + hi exceeds Integer.MAX_VALUE and overflows to a negative integer, causing an infinite loop.
  • hi = mid: If mid is bad, it might itself be the very first bad version. Setting hi = mid - 1 would incorrectly discard it.

07Why it works

The version status follows a step function: once a version is bad, every subsequent version is also bad. Testing the midpoint tells us which side of the boundary we are on. By discarding the good prefix when mid is good, and keeping mid as the upper bound when mid is bad, the search interval [lo, hi] always encapsulates the first bad version. When lo meets hi, the exact transition point is isolated.

Invariant: The first bad version always lies within [lo, hi].

08Time and space

  • Time: O(log n). Even when n = 2³¹ − 1, at most 31 API calls are made.
  • Space: O(1). Only two pointer variables are used.

09Edge cases

InputOutputWhy it matters
n = 1, bad = 11Single version, immediately bad
n = 2, bad = 11First version in a pair is bad
n = 2, bad = 22Last version in a pair is bad
n = 10, bad = 1010Only the very last version is bad
n = 2126753390, bad = 17027667191702766719Huge values testing 32-bit integer overflow

10Common mistakes

  • Using (lo + hi) / 2. When lo and hi are large, this causes a 32-bit signed overflow into negative territory.
  • Writing hi = mid - 1 when mid is bad. If mid happens to be the first bad version, decrementing hi eliminates the answer completely.
  • Calling the API twice per iteration. Writing if (isBadVersion(mid)) ... else if (!isBadVersion(mid)) calls the expensive API redundantly. Test once per midpoint.

11Other approaches

ApproachTimeSpaceUse when
Linear scanO(n)O(1)Never with large n
Binary searchO(log n)O(1)Default interview answer
Exponential + binary searchO(log b)O(1)If the bug is known to be very recent
RecursionO(log n)O(log n)Stack frames waste memory

12In the interview

  • What if the API call is extremely slow (e.g., runs a 10-minute integration test suite)? Exponential search starting from recent commits can isolate an initial upper bound before switching to binary search.
  • Generalization: Any question asking to find the boundary between false and true where the predicate is monotonic can be solved with this exact template.

13Check your understanding

Quiz · 2 questions

0 of 2 answered

  1. 1. Why is it critical to write lo + (hi - lo) / 2 in First Bad Version?

  2. 2. If isBadVersion(mid) returns true, why do we set hi = mid instead of hi = mid - 1?

14Solve it yourself

Try it on LeetCode #278.