Skip to content

Commit 10c76f0

Browse files
committed
bad version
1 parent 91ca7fc commit 10c76f0

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

278.first_bad_version/bad.go

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// 278. First bad version
2+
// Topics: 'Binary Search', 'Interactive'
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 returns 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 1:
11+
12+
// Input: n = 5, bad = 4
13+
// Output: 4
14+
// Explanation:
15+
// call isBadVersion(3) -> false
16+
// call isBadVersion(5) -> true
17+
// call isBadVersion(4) -> true
18+
// Then 4 is the first bad version.
19+
20+
// Example 2:
21+
22+
// Input: n = 1, bad = 1
23+
// Output: 1
24+
25+
// Constraints:
26+
27+
// 1 <= bad <= n <= 231 - 1
28+
29+
package firstbadversion
30+
31+
func firstBadVersion(n int) int {
32+
L, R := 0, n
33+
34+
var bad int
35+
for L <= R {
36+
mid := L + (R-L)/2
37+
isBad := isBadVersion(mid)
38+
39+
if isBad {
40+
bad = mid
41+
R = mid - 1
42+
} else {
43+
L = mid + 1
44+
}
45+
}
46+
return bad
47+
}
48+
49+
func isBadVersion(v int) bool {
50+
// dummy
51+
return false
52+
}

0 commit comments

Comments
 (0)