First bad version
A product has versions numbered 1 to n, in release order. One release introduced a bug, and every later version carried it: once a version is bad, all versions after it are bad too.
You get n and a function is_bad(v) that returns True when version v is bad and False when it is good. At least one version is bad. Return the number of the first bad version.
Each call to is_bad is expensive (picture a full build and test run), so make as few calls as you can. The tests count them: at most 32 calls, even when n is 2,147,483,647 (that is 231 - 1). Never call is_bad with a number outside 1 to n.
The examples write is_bad as a lambda, a function written as one expression: lambda v: v >= 4 takes v and returns whether it is at least 4.
n = 5, is_bad = lambda v: v >= 4Output4Versions 1 to 3 are good, and 4 and 5 are bad. The bug arrived in version 4.
n = 6, is_bad = lambda v: v >= 1Output1Every version is bad, so the first bad one is version 1.
n = 1, is_bad = lambda v: v >= 1Output1There is one version, and since at least one is bad, it is that one.
1 ≤ n ≤ 231 - 1
At least one version is bad, so
is_bad(n)is True.is_badanswers False for every version before the first bad one and True from there on.At most 32 calls to
is_badper answer.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.