Created
April 17, 2023 21:24
-
-
Save optimistiks/fae5f9d0c0a71419109cb4910ad9723c to your computer and use it in GitHub Desktop.
Suppose you have n versions with the IDs [1,2,...,n], and you have access to an API function that returns TRUE if the argument is the ID of a bad version. Your task is to find the first bad version, which is causing all the later ones to be bad. You have to implement a solution with the minimum number of API calls.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export function firstBadVersion(n) { | |
| // -- DO NOT CHANGE THIS SECTION | |
| versionApi.n = n; | |
| // -- | |
| let start = 1; | |
| let end = n; | |
| let count = 0; | |
| while (start < end) { | |
| let mid = Math.floor((start + end) / 2); | |
| count += 1; | |
| if (isBadVersion(mid)) { | |
| // we dont do end = mid - 1 here because | |
| // if mid is actually the first bad version, | |
| // doing -1 will shift us to the left of it, | |
| // and we will never return back to it | |
| end = mid; | |
| } else { | |
| start = mid + 1; | |
| } | |
| } | |
| return [start, count]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment