Skip to content

Commit 33fa48f

Browse files
First Bad Version : Accepted
1 parent 62c54ce commit 33fa48f

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ My accepted leetcode solutions to some of the common interview problems.
4949
- [Median of Two Sorted Arrays](problems/src/binary_search/MedianOfTwoSortedArrays.java) (Hard)
5050
- [Pow(x, n)](problems/src/binary_search/PowXN.java) (Medium)
5151
- [Find Peak Element](problems/src/binary_search/FindPeakElement.java) (Medium)
52+
- [First Bad Version](problems/src/binary_search/FirstBadVersion.java) (Easy)
5253

5354
#### [Bit Manipulation](problems/src/bit_manipulation)
5455

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package binary_search;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 29/11/2017.
5+
*
6+
* You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version
7+
* of your product fails the quality check. Since each version is developed based on the previous version,
8+
* all the versions after a bad version are also bad.
9+
10+
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the
11+
following ones to be bad.
12+
13+
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to
14+
find the first bad version. You should minimize the number of calls to the API.
15+
*/
16+
public class FirstBadVersion {
17+
public static void main(String[] args) throws Exception{
18+
System.out.println(new FirstBadVersion().firstBadVersion(2126753390));
19+
}
20+
21+
public int firstBadVersion(int n) {
22+
int low = 0, high = n;
23+
while(low < high){
24+
int mid = (low + high) >>> 1;
25+
if(isBadVersion(mid)){
26+
high = mid;
27+
} else low = mid + 1;
28+
}
29+
return high;
30+
}
31+
32+
private boolean isBadVersion(int n){
33+
if(n >= 1702766719)
34+
return true;
35+
return false;
36+
}
37+
}

0 commit comments

Comments
 (0)