Skip to content

Commit 175b092

Browse files
authored
Create First_Bad_Version.java
1 parent 2d643d8 commit 175b092

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

BinarySearch/First_Bad_Version.java

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
//Leetcode 278. First Bad Version
2+
//Question - https://leetcode.com/problems/first-bad-version/
3+
4+
/*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.
5+
6+
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.
7+
8+
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
9+
10+
Example:
11+
12+
Given n = 5, and version = 4 is the first bad version.
13+
14+
call isBadVersion(3) -> false
15+
call isBadVersion(5) -> true
16+
call isBadVersion(4) -> true
17+
18+
Then 4 is the first bad version.*/
19+
20+
/* The isBadVersion API is defined in the parent class VersionControl.
21+
boolean isBadVersion(int version); */
22+
23+
public class Solution extends VersionControl {
24+
public int firstBadVersion(int n) {
25+
int low = 1;
26+
int high = n;
27+
28+
while(low < high){
29+
int mid = low + (high-low)/2;
30+
boolean isBad = isBadVersion(mid);
31+
32+
if(isBad){
33+
high = mid;
34+
}
35+
else low = mid + 1;
36+
}
37+
38+
return low;
39+
}
40+
}
41+
42+
//OR
43+
44+
public class Solution extends VersionControl {
45+
public int firstBadVersion(int n) {
46+
int low = 1;
47+
int high = n;
48+
int result = -1;
49+
50+
while(low<=high){
51+
int mid = low + (high-low)/2;
52+
boolean isBad = isBadVersion(mid);
53+
54+
if(isBad){
55+
result = mid;
56+
high = mid-1;
57+
}
58+
else low = mid + 1;
59+
}
60+
61+
return result;
62+
}
63+
}

0 commit comments

Comments
 (0)