First Bad Version

Easy
Binary Search

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
Explanation: Version 1 is the first and only bad version.

Constraints

  • 1 <= bad <= n <= 2^31 - 1
Show Hints (3)
Hint 1: This is a classic binary search for a decision boundary. You are looking for the transition point from good to bad.
Hint 2: If version mid is bad, the first bad version is mid or before it. If mid is good, the first bad version is after mid.
Hint 3: Be careful with integer overflow when calculating mid with large values of n.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?