The brute-force solution checks every version sequentially, leading to:
The optimal solution uses binary search to find the first bad version in O(log n) time complexity:
The “First Bad Version” problem asks us to find the earliest version of a product that fails quality control. You are given a function isBadVersion(version)
which returns true
if a version is bad and false
otherwise. Versions are developed sequentially, and once a bad version appears, all subsequent versions are also bad.
Your task is to determine the first bad version out of n
versions with the minimum number of calls to isBadVersion
.
This problem is an application of binary search — a core algorithmic concept that enables efficient searching over sorted data. It also simulates real-world problems such as debugging a regression bug in a sequence of software builds or identifying the version that introduced a breaking change.
Since the list of versions has a sorted property (all versions before the first bad one are good, and all after are bad), we can use binary search to efficiently locate the first bad version.
left = 1
and right = n
.left < right
:
mid = Math.floor((left + right) / 2)
.isBadVersion(mid)
:
true
, the first bad version could be mid
or earlier → set right = mid
.false
, the first bad version is later → set left = mid + 1
.left
will point to the first bad version. Return left
.
Suppose n = 5
and isBadVersion
returns true
starting from version 4:
The first bad version is 4
, and we found it using only two API calls instead of five.
Time Complexity: O(log n), as binary search cuts the search space in half each time.
Space Complexity: O(1), using constant additional space.
The “First Bad Version” problem is a classic binary search use case that highlights how to efficiently search for the first occurrence of a condition in a sorted dataset. It's highly relevant for software testing and debugging and teaches how to reduce API calls or checks in performance-critical applications.