Introduction
You are a product manager and currently 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.
|
|
|
|
Process
Using a binary search done in Leetcode Binary Search 704, I was able to get the first bad version.
First, I initialised my left
variable to 1
as the lower limit was 1
and I couldn’t start from 0. I initialised right to be n
for the number of versions.
In the same while loop, I calculated the mid index again, but this time with right shift. I first checked with the isBadVersion
API for the midpoint. If it is true, I’ll set the firstIndex
variable to the midpoint, and the right index to mid - 1
to check the left side.
If the first condition is not met, I’ll check the next half by updating mid + 1
in the while loop.
At the end of the loop, firstIndex
is returned as the First Bad Version.
This solution takes a Time Complexity of $O(\log n)$ and Space Complexity of $O(1)$
Solution
|
|
Afterthoughts
This is almost a duplicate of Leetcode Binary Search 704, where binary search is used as the most efficient algorithm, splitting the sorted array into half each time through the iteration to search for the values required. I need more practice to be familiar and comfortable with these searching algorithms.