LeetCode: First Bad Version Solution

Luckily, mid calculation in JS did not throw overflow error

Approach

"all the versions after a bad version are also bad"

Example 1

11 2 3 4 5
2G G G B B
3L M H
4
51 2 3 4 5
6G G G B B
7 L H

Example 2

11 2 3 4 5
2G B B B B
3L M H
4
51 2 3 4 5
6G B B B B
7L M H
8
91 2 3 4 5
10G B B B B
11 L H

Implementation

1var solution = function (isBadVersion) {
2 return function (n) {
3 let lo = 1
4 let hi = n
5
6 while (lo < hi) {
7 let mid = Math.floor((lo + hi) / 2)
8 if (isBadVersion(mid) === false) {
9 lo = mid + 1
10 } else {
11 hi = mid
12 }
13 }
14
15 return lo
16 }
17}

References

Original problem

Comments

Loading comments...

Tags

leetcode

binary search

Next Post

LeetCode: Two Sum II - Input array is sorted

If trying to explain takes time, go on

Previous Post

HoningJS

Search Posts