Algorithms · Binary search

First Bad Version

A bug crept in at some version. Find the first broken one.

The problem

Your app has versions 0, 1, 2…. At some point a bug crept in, and every version after it is broken too. versions[i] is True if version i is broken. Return the first broken version. (LeetCode gives you a function to call instead of a list.)

first_bad([False, False, True, True])2
first_bad([True])0
Binary search. Throw away half. Guess my number from 1 to 100. “Higher!” “Lower!” Seven guesses are always enough.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def first_bad(versions):take broken (True) / fine (False) for each version
for i in range(len(versions)):check each version, oldest first
if versions[i]:broken?
return ithe first broken one

Now ask: what if there were a billion?

This is exactly git bisect: among 10,000 commits it finds the one that broke your app in about 14 tests. Linux kernel developers use it to hunt bugs across years of history.

Aim for O(log n)🧩 classic

Think it through

Version 50 is broken. Where is the first bad one?

  • After 50
  • At 50 or before it
Show the answer

At 50 or before it. Once broken, always broken after. So a broken middle means the first bad one is there or earlier. A working middle means later.

Each check takes ten minutes (build and test). Why does that make halving matter so much?

  • It doesn’t
  • It turns hundreds of checks into about ten
Show the answer

It turns hundreds of checks into about ten. When a check is expensive, the number of checks is everything. This is exactly git bisect: find the commit that broke things in a handful of builds.

Stuck? 3 nudges, smallest first
  1. Checking a version can be slow in real life (you have to build and test it). How few checks can you get away with?
  2. Test the middle version. If it’s broken, the first bad one is there or earlier. If it’s fine, it’s later.
  3. Keep lo, hi. While lo < hi: if versions[mid] is broken, hi = mid, else lo = mid + 1. Return lo.

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def first_bad(versions):take broken (True) / fine (False) for each version
lo, hi = 0, len(versions) - 1the first bad one is somewhere in here
while lo < hi:until only one version is left
mid = (lo + hi) // 2test the middle version
if versions[mid]:broken?
hi = midthe first bad one is here or earlier
else:fine
lo = mid + 1the first bad one is later
return lothe only version left

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with binary search