First Bad Version

IF
AlgoAxiomStaff Engineers
JSTS
Easy20 mins

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 versions after a bad version are also bad.

Given n versions [1, 2, ..., n], find the first bad version which causes all the following ones to be bad.

You are given an API isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version, minimizing the number of API calls.

In this implementation, you receive n and bad (the first bad version) as parameters.

Examples

Example 1:

Input: n = 5, bad = 4

Output: 4

Explanation: isBadVersion(3) = false, isBadVersion(4) = true, isBadVersion(5) = true. So 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1

Output: 1

Constraints

  • 1 <= bad <= n <= 2^31 - 1
Source: Modified Binary Search pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle