Your team ships versions numbered 1 to n, each built on top of the one before it. At some point a broken change slipped in: that version is bad, and so is every version after it. The latest version, n, is known to be bad.
You cannot see the code, but you can call a helper, isBadVersion(version) (is_bad_version in Python), which tells you whether a version is bad. Return the first bad version, and make as few calls to the helper as you can.
Example 1
Input: n = 8, bad = 6 Output: 6 Why: versions 1 to 5 are good, 6 to 8 are bad
2 more examples and the constraints
Example 2
Input: n = 1, bad = 1 Output: 1 Why: the only version is the bad one
Example 3
Input: n = 5, bad = 1 Output: 1 Why: every version is bad, so the first is version 1
Constraints
- 1 ≤ bad ≤ n ≤ 2,147,483,647 (2^31 − 1)
- bad is the first bad version; your code only learns about it through isBadVersion
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every version in orderO(n)
- Binary search for the first badO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Calls to isBadVersion for n = 2^31 − 1 | Verdict |
|---|---|---|---|
| Check every version in order | O(n) | Up to two billion calls | |
| Binary search for the first bad | O(log n) | Best; 31 calls at most |
n = number of versions.
Edge cases to test
- One version. n = 1 means version 1 is bad; the loop never runs.
- Every version is bad. The answer is 1; the search keeps moving hi down to it.
- Only the last version is bad. The answer is n; lo keeps moving up to it.
- The largest n. With n = 2,147,483,647,
lo + hioverflows a 32-bit int on the first step.
Common mistakes
- Computing mid as (lo + hi) / 2, which overflows for large n in Java and C++.
- Setting hi = mid − 1 when mid is bad, which can skip past the first bad version.
- Looping while lo ≤ hi with hi = mid, which never ends once lo equals hi.
How to talk through it
- 1Clarify. Is version n always bad? Is the cost the number of calls to isBadVersion?
- 2Give the scan. Check versions in order; it works but can take n calls.
- 3Spot the flip. Good versions come first and bad ones after, so binary search for where it switches.
- 4Code the bounds. Bad mid keeps mid as hi, good mid moves lo past it, and the midpoint avoids overflow.
- 5Test out loud. Run n = 1, every version bad, only the last bad, and n = 2^31 − 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?