First Bad Version - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
n = 5, bad = 4
›
Output:
4
💡 Note:
Versions 1, 2, 3 are good. Version 4 is the first bad version, so versions 4 and 5 are bad. Using binary search: check version 3 (good), then check version 4 (bad), so return 4.
Example 2 — First Version Bad
$
Input:
n = 1, bad = 1
›
Output:
1
💡 Note:
Only one version exists and it's bad, so return 1.
Example 3 — Last Version Bad
$
Input:
n = 3, bad = 3
›
Output:
3
💡 Note:
Versions 1 and 2 are good, version 3 is the first (and only) bad version.
Constraints
- 1 ≤ bad ≤ n ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Range of versions [1, 2, ..., n] with unknown first bad version
2
Process
Use binary search to efficiently locate the boundary
3
Output
Return the first version that is bad
Key Takeaway
🎯 Key Insight: The versions form a sorted pattern (good, good, ..., bad, bad) perfect for binary search
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code