LeetCode: First Bad Version Solution
Luckily, mid calculation in JS did not throw overflow errorApproach
"all the versions after a bad version are also bad"
Example 1
11 2 3 4 52G G G B B3L M H451 2 3 4 56G G G B B7 L H
Example 2
11 2 3 4 52G B B B B3L M H451 2 3 4 56G B B B B7L M H891 2 3 4 510G B B B B11 L H
Implementation
1var solution = function (isBadVersion) {2 return function (n) {3 let lo = 14 let hi = n56 while (lo < hi) {7 let mid = Math.floor((lo + hi) / 2)8 if (isBadVersion(mid) === false) {9 lo = mid + 110 } else {11 hi = mid12 }13 }1415 return lo16 }17}
References
Comments
Loading comments...
Tags
leetcode
binary search
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.