
First Bad Version
Write a C program to find the first bad version of a product. 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.
Example 1
- Input: n = 5, bad = 4
- Output: 4
- Explanation:
We have versions [1, 2, 3, 4, 5] with version 4 as the first bad version.
isBadVersion(3) -> false, isBadVersion(4) -> true, therefore version 4 is the first bad version.
Example 2
- Input: n = 1, bad = 1
- Output: 1
- Explanation:
We have only one version, which is version 1.
isBadVersion(1) -> true, therefore version 1 is the first bad version.
Constraints
- 1 ≤ bad ≤ n ≤ 2^31 - 1
- You should call the isBadVersion API as few times as possible
- Time Complexity: O(log n)
- Space Complexity: O(1)
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Consider using binary search to minimize the number of API calls
- Initialize your search range from 1 to n
- For each mid value, check if it's a bad version using the isBadVersion API
- If mid is a bad version, search in the left half (including mid)
- If mid is not a bad version, search in the right half (excluding mid)
- Continue until the search range is narrowed down to a single version