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: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version.
Example 2:
Input: n = 1, bad = 1 Output: 1
Constraints:
1 <= bad <= n <= 231 - 1This approach uses the concept of binary search to efficiently find the first bad version by minimizing the number of calls made to the given isBadVersion API. By leveraging binary search, we can reduce the problem set size by half with each iteration, therefore achieving O(log n) time complexity.
The code above implements the binary search algorithm. It initializes two pointers, left and right, to perform the search. If isBadVersion(mid) is true, the first bad version must be at mid or to its left, hence right is adjusted. Otherwise, the bad version must be to the right of mid, hence left is adjusted. The loop continues until left meets right, at which point the first bad version is identified.
C++
Java
Python
C#
JavaScript
Time Complexity: O(log n)
Space Complexity: O(1)
This approach explores a recursive implementation of the binary search technique to identify the first bad version. Employing recursion allows the continual division of the search problem into smaller subproblems until the solution is found.
The solution leverages a recursive helper function, binarySearch, to apply the binary search paradigm. isBadVersion checks are made mid way through the current range of versions. The range is recursively narrowed down based on this evaluation until left identifies the first bad version.
C++
Java
Python
C#
JavaScript
Time Complexity: O(log n)
Space Complexity: O(log n) - due to recursion stack
| Approach | Complexity |
|---|---|
| Binary Search Optimization | Time Complexity: |
| Recursive Binary Search Method | Time Complexity: |
First bad version | Leetcode #278 • Techdose • 49,521 views views
Watch 9 more video solutions →Practice First Bad Version with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor