First Bad Version

Easy Binary Search

Problem

You have n versions [1..n]. A function isBadVersion(v) returns true if version v is bad. Once a version is bad, every subsequent version is bad too. Find the FIRST bad version using as few calls as possible.

Example 1 Input: n = 5, first bad = 4 Output: 4
Example 2 Input: n = 1, first bad = 1 Output: 1

Constraints

Approach — Binary Search

This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(log n) time.

Solution code

Python

class Solution:
    def firstBadVersion(self, n):
        lo, hi = 1, n
        while lo < hi:
            mid = (lo + hi) // 2
            if isBadVersion(mid):
                hi = mid
            else:
                lo = mid + 1
        return lo

Java

class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int lo = 1, hi = n;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (isBadVersion(mid)) hi = mid;
            else                   lo = mid + 1;
        }
        return lo;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve First Bad Version interactively → ← All solutions