Search⌘ K
AI Features

First Bad Version

Understand how to apply modified binary search to detect the earliest defective version in a product sequence. Learn to minimize the number of API calls and grasp problem-solving strategies relevant for coding interviews.

Statement

You are managing a product development team, and the latest release has failed quality checks. Because each version is built on top of the previous one, once a version is bad, every version after it is also bad.

You are given an array of n versions [1,2,,n][1, 2, …, n], and your task is to determine the first version in this sequence that is bad—the version that causes all later versions to be bad as well.

You have access to an API isBadVersion(version) that returns TRUE if a given version is bad.

Your task is to find the first bad version while minimizing the number of calls to this API.

Constraints:

  • 11 \leq bad \leq n 105\leq 10^5

Examples

canvasAnimation-image
1 / 3

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

First Bad Version

1.

Given n = 1010, if version 77 is the first bad version, how many API calls are required to find it?

A.

11

B.

22

C.

33

D.

44


1 / 3

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in the following coding playground.

JavaScript
usercode > Solution.js
/* The this.isBadVersion(version) API is already defined for you
which returns TRUE if a current version is bad. */
import BadVersion from './BadVersion.js';
class Solution extends BadVersion {
constructor(bad) { super(bad); }
firstBadVersion(n) {
// Replace this placeholder return statement with your code
return 0;
}
}
export default Solution;
First Bad Version