Statement
Solution
Naive approach
The naive approach is to find the first bad version in the versions range by linear search. We traverse the whole version range one element at a time until we find the target version.
The time complexity of this approach is
Optimized approach using modified binary search
In this solution we use binary search to check the middle version to determine if it is bad.
If the middle version is good, the first bad version must be later in the range, so the first half of the range is skipped.
If the middle version is bad, we focus on the first half of the range to find the first bad version, allowing us to skip the second half.
We repeat the process after identifying which half of the range to search. For the identified half, we check the middle version again to decide whether to search the first or second half of the current range. This process continues until the first bad version is found.
Binary search is the most suitable approach for finding the first bad version because the versions are sorted from n
. It executes in
Here’s the step-by-step implementation of the solution:
Initialize
first = 1
andlast = n
to define the search range.While
first <= last
, perform the following steps:Calculate
mid = first + (last - first) / 2
to find the middle value.If
is_bad_version(mid)
is TRUE:Set
last = mid - 1
because the first bad version is present in the left half of the versions.
Otherwise:
Set
first = mid + 1
because the first bad version is present in the right half of the versions.
Return
first
, which now represents the first bad version.
Let’s look at the following illustration to get a better understanding of the solution: