Skip to content

Commit 739705e

Browse files
Create First Bad Version.md
1 parent a73f21a commit 739705e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

JS-Algo/First Bad Version.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
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.
2+
3+
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.
4+
5+
You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
6+
7+
<img width="475" alt="Screen Shot 2021-11-13 at 22 06 30" src="https://user-images.githubusercontent.com/37787994/141668388-998ea209-0021-47e0-9803-27f878793d85.png">
8+
9+
10+
```JS
11+
/**
12+
* Definition for isBadVersion()
13+
*
14+
* @param {integer} version number
15+
* @return {boolean} whether the version is bad
16+
* isBadVersion = function(version) {
17+
* ...
18+
* };
19+
*/
20+
21+
/**
22+
* @param {function} isBadVersion()
23+
* @return {function}
24+
*/
25+
var solution = function(isBadVersion) {
26+
/**
27+
* @param {integer} n Total versions
28+
* @return {integer} The first bad version
29+
*/
30+
return function(n) {
31+
let start = 1, end = n;
32+
while(start < end) {
33+
let mid = Math.floor((start + end) / 2);
34+
if(isBadVersion(mid)) {
35+
end = mid;
36+
}
37+
else {
38+
start = mid + 1
39+
}
40+
}
41+
return start
42+
};
43+
};
44+
```

0 commit comments

Comments
 (0)