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
First Bad Version - Binary Search INPUT Versions [1, 2, ..., n] 1 Good 2 Good 3 Good 4 Bad 5 Bad First Bad n = 5 bad = 4 isBadVersion(v) API Find first bad version with minimum API calls ALGORITHM STEPS 1 Initialize Pointers left=1, right=5 2 Binary Search mid = (left+right)/2 3 Check isBadVersion If bad: search left 4 Narrow Range If good: search right Iterations: 1: mid=3, isBad=false left=4, right=5 2: mid=4, isBad=true left=4, right=4 3: left==right, done! return 4 FINAL RESULT 1 2 3 4 5 First Bad Version Found! Output 4 OK - Verified! Version 4 is first bad Performance API calls: 2 (vs 4 linear) Time: O(log n) Key Insight: Binary search works because all bad versions are contiguous from first bad to n. If mid is bad, first bad is at mid or before it (search left). If mid is good, search right. This reduces search space by half each iteration, achieving O(log n) API calls. TutorialsPoint - First Bad Version | Binary Search Optimal Approach
Asked in
Facebook 45 Google 38 Microsoft 32 Amazon 28
156.0K Views
High Frequency
~15 min Avg. Time
4.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen