The First Bad Version interview question is a classic search optimization problem. You are a product manager and have versions of a product. Once a version is "bad," all subsequent versions are also bad. You are given an API isBadVersion(version) and need to find the first bad version while minimizing the number of API calls.
This is one of the most common questions at Google, Microsoft, and Amazon. It tests your fundamental understanding of Binary Search. It evaluations if you can recognize that a linear search () is sub-optimal for a monotonic property (a sequence of False values followed by True values). It's the "Hello World" of Binary Search interview patterns.
This problem follows the Binary Search on a Monotonic Property pattern.
left = 1, right = n.mid = left + (right - left) / 2.isBadVersion(mid) is true, then mid could be the first bad version, or the first bad version is to the left. Move right = mid.isBadVersion(mid) is false, all versions up to mid are good. Move left = mid + 1.left == right, you have found the first bad version., First bad version is 4.
left=1, right=5, mid=3. isBad(3) is false. left = 4.left=4, right=5, mid=4. isBad(4) is true. right = 4.left == right. Result: 4.(left + right) / 2 which can exceed the integer limit for large . Always use left + (right - left) / 2.left <= right and right = mid - 1, which requires more complex logic to return the correct boundary. The left < right and right = mid approach is usually cleaner for finding the first occurrence.Binary Search is the standard solution for finding a "transition point" in any sorted or monotonic space. Practice identifying the "property" that allows you to discard half the search space.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Guess Number Higher or Lower | Easy | Solve | |
| Search in a Sorted Array of Unknown Size | Medium | Solve | |
| Find the Index of the Large Integer | Medium | Solve | |
| Number of Equal Numbers Blocks | Medium | Solve | |
| Find in Mountain Array | Hard | Solve |