Search⌘ K
AI Features

First Bad Version

Explore how to determine the earliest bad version in a sequence where all subsequent versions are flawed. This lesson teaches you to efficiently use a modified binary search technique to minimize API calls while isolating the problem version. Understand the logic behind this approach and implement it practically.

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.

Java
usercode > Solution.java
/* The isBadVersion(version) API is already defined for you
which returns TRUE if a current version is bad. */
public class Solution extends BadVersion {
public Solution(int bad) { super(bad); }
public int firstBadVersion(int n) {
// Replace this placeholder return statement with your code
return 0;
}
}
First Bad Version